package cn.ainit.sys.framework;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.ainit.sys.common.dao.Pagination;
import cn.ainit.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ainit.common.ReturnObject;
import cn.ainit.model.ModelReturnObj;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.framework.entity.ColnPerms;
import cn.ainit.sys.framework.entity.SysButtons;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.models.ModelReceiveObj;
import cn.ainit.sys.pagescript.entity.ReceiveParam;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.DataGridReceiveParams;
import cn.ainit.sys.query.entity.QueryJson;
import cn.ainit.sys.ui.forms.Columns;
import cn.ainit.sys.utils.UUID32;

@Controller
@RequestMapping("/framework")
public class FrameworkController {

	private FrameworkService frameworkService;

	@Resource
	public void setFrameworkService(FrameworkService frameworkService) {
		this.frameworkService = frameworkService;
	}

	/**
	 * 查询列
	 *
	 * @param colId
	 * @param flag
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/columnList")
	@ResponseBody
	public List<SysColumns> columnList(String colId, String flag, HttpServletRequest request) throws Exception {
		try {
			List<SysColumns> list = frameworkService.colList(colId, flag);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询按钮
	 *
	 * @param butnId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/buttonsList")
	@ResponseBody
	public List<SysButtons> buttonsList(String butnId, HttpServletRequest request) throws Exception {
		try {
			List<SysButtons> list = frameworkService.butnList(butnId);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询按钮 [多个ID]
	 *
	 * @param butnId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/buttonsListC")
	@ResponseBody
	public List<SysButtons> buttonsListC(String butnId, HttpServletRequest request) throws Exception {
		try {
			String[] butA = butnId.split(";");
			List<SysButtons> list = new ArrayList<SysButtons>();
			for (int i = 0; i < butA.length; i++) {
				List<SysButtons> listTmp = frameworkService.butnList(butA[i]);
				list.addAll(listTmp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询按钮和列（当查询单录单界面的时候请求这个方法）
	 *
	 * @param colId   列的ID
	 * @param flag    查询那些列的标志
	 * @param butnId  按钮ID
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/singlePage")
	@ResponseBody
	public QueryJson makeSinglePage(String colId, String flag, String butnId, HttpServletRequest request) throws Exception {
		QueryJson queryJson = new QueryJson();
		try {
			List<SysColumns> list = frameworkService.colList(colId, flag);
			List<SysButtons> butnList = frameworkService.butnList(butnId);
			queryJson.setColumns(list);
			queryJson.setButtons(butnList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	/**
	 * 返回QueryJson  有datagrid中的Columns
	 *
	 * @param dsId     Datastore的ID  要查询Sql
	 * @param colId    列的Id
	 * @param execFlag 判断是否执行存储过程的标志
	 * @param flag     判断查询某些列的标志
	 * @param id       执行存储过程时传的选题ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listQueryJson")
	@ResponseBody
	public QueryJson listQueryJson(String dsId, String colId, String flag, String execFlag, String id, HttpServletRequest request) throws Exception {
		try {
			QueryJson queryJson = new QueryJson();
			List<SysColumns> list = frameworkService.colList(colId, flag);   //datagrid中的列
			DataStore dataStore = new DataStore();
			dataStore = frameworkService.getDataStoreById(dsId);
			if (execFlag != null && execFlag.equals("T")) {   //如果execFlag为T的话则执行存储过程   并从新得到Rows
				String whereStr = " where 1=1 ";
				String sql = "";
				//执行初始化存储过程,相当于前置存储过程    id 是执行存储过程的时候的参数
				//	STRING sql=“BEGIN PK_BJ_XT.up_GetXtManage('BA734CA0DE8F48CBAE31E3219BE49F30','00000'); END;”
				if (frameworkService.execLink(id, "00000")) {
					sql = dataStore.getSqlText() + whereStr + " and XT_ID = '" + id + "'";
					//执行select 得到结果集
					//objects = (List<Object>) frameworkService.queryRowsBySql(sql);
				}
			} else {
				//objects = (List<Object>) frameworkService.queryRowsBySql(dataStore.getSqlText());
			}
			queryJson.setColumns(list);
			//取datagrid中的数据，请到每个模块写
			//queryJson.setRows(objects);
			queryJson.setUrl(request.getContextPath() + "/framework/loadData?dsId=" + dsId);
			return queryJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * format: 01 获取该字段最大值
	 * format：02 sql语句
	 * format: 03 sql语句获取
	 *
	 * @param format
	 * @param oldValue
	 * @return
	 */

	public String formatValues(String format, String oldValue, String formatCont) throws Exception {
		String value = null;
		if (format == null || format.trim().equals("")) {
			return oldValue;
		}
		String[] formatArr = format.split(";");
		if (formatArr[0].equals("01")) {
			value = UUID32.newGuid();
		} else if (formatArr[0].equals("02")) {
			//FOZT00001
			if (formatArr.length == 2 && !formatArr[1].equals("")) {
				value = frameworkService.getMaxPkStr(formatArr[1]);
				int index = 0;
				if (value == null || value.equals("")) {
					if (formatCont == null || formatCont.equals("")) {
						throw new RuntimeException("主键类型为设置");
					}
					value = formatCont;
				}
				for (int i = 0; i < value.length(); i++) {
					if (value.charAt(i) >= '0' && value.charAt(i) < '9') {
						index = i;
						break;
					}
				}
				String numTmp = String.valueOf(Double.parseDouble(value.substring(index)) + 1).split("\\.")[0];
				if (numTmp.length() != value.substring(index).length()) {
					int colength = value.substring(index).length() - numTmp.length();
					for (int i = 0; i < colength; i++) {
						numTmp = "0" + numTmp;
					}
				}
				value = value.substring(0, index) + numTmp;
			} else {
				return "";
			}
		}
		return value;
	}

	//保存数据
	@RequestMapping("/saveInfo")
	@ResponseBody            //接受参数			按钮ID			按钮权限 			对象ID
	public ReturnObject saveButClick(ReceiveParam params, String dsId, String colId, HttpServletRequest request) {
		ReturnObject returnObject = new ReturnObject();
		try {
			//1.判断按钮权限

			//2.获取ds要更新的表
			//			ConfigObject configObject = pageCommonService.findConfigObj(configId);
			//3.获取所有字段
			//     a.取出主键  设置主键值
			//     b.将界面字段遍历  所有的字段  有则留  添加到相应的字段
			//			String colnsIdStr = configObject.getUiColDsId();
			DataStore dataStore = frameworkService.getDataStoreById(dsId);
			List<SysColumns> cpColumns = frameworkService.colList(colId, "");
			Map<String, SysColumns> colnMap = new HashMap<String, SysColumns>();//数据库中有属性、不是主键字段
			Map<String, SysColumns> pkColnMap = new HashMap<String, SysColumns>();//数据库中主键字段
			String[] paramsKandV = params.getSqlParams();//界面参数
			List<String> nameValue = new ArrayList<String>();//返回界面需要填充的参数 【返回界面是的操作】
			//a.取出主键  设置主键值
			for (int i = 0; i < cpColumns.size(); i++) {
				if (cpColumns.get(i).getJavaProperty() != null && !cpColumns.get(i).getJavaProperty().equals("")) {
					if (cpColumns.get(i).getPrimaryKey() != null && cpColumns.get(i).getPrimaryKey().equals("T")) {
						pkColnMap.put(cpColumns.get(i).getJavaProperty(), cpColumns.get(i));
					} else {
						colnMap.put(cpColumns.get(i).getJavaProperty(), cpColumns.get(i));
					}
				}
			}
			// b.将界面字段遍历  所有的字段  有则留  添加到相应的字段
			//    获取主键生成方式     format = '01'  获取32位码   '02'  sequence  'idStr' sql where id  '04'   '05'    '06'
			StringBuffer keyStr = new StringBuffer("(");//sql字段
			StringBuffer valueStr = new StringBuffer("(");//占位符
			StringBuffer values = new StringBuffer("");//值的字符串
			String[] tmpKV = new String[2];
			for (int i = 0; i < paramsKandV.length; i++) {
				tmpKV = paramsKandV[i].split("\\=");
				if (colnMap.containsKey(tmpKV[0])) {
					keyStr.append(tmpKV[0] + ",");
					valueStr.append("?,");
					String tmpValue = formatValues(colnMap.get(tmpKV[0]).getFormat() == null ? "" : colnMap.get(tmpKV[0]).getFormat(), tmpKV[1], colnMap.get(tmpKV[0]).getFormatCont());
					values.append(tmpValue + "|");
					if (!tmpValue.equals(tmpKV[1])) {
						nameValue.add(tmpKV[0] + "=" + tmpValue);
					}
				} else if (pkColnMap.containsKey(tmpKV[0])) {
					keyStr.append(tmpKV[0] + ",");
					valueStr.append("?,");
					String tmpValue = formatValues(pkColnMap.get(tmpKV[0]).getFormat() == null ? "" : pkColnMap.get(tmpKV[0]).getFormat(), tmpKV[1], pkColnMap.get(tmpKV[0]).getFormatCont());
					values.append(tmpValue + "|");
					if (!tmpValue.equals(tmpKV[1])) {
						nameValue.add(tmpKV[0] + "=" + tmpValue);
					}
					pkColnMap.remove(tmpKV[0]);
				}
			}
			//  c.拼接剩余的主键
			for (Iterator it = pkColnMap.entrySet().iterator(); it.hasNext(); ) {
				Columns columns = (Columns) it.next();
				keyStr.append(columns.getJavaProperty() + ",");
				valueStr.append("?,");
				values.append(formatValues(pkColnMap.get(tmpKV[0]).getFormat(), tmpKV[1], pkColnMap.get(tmpKV[0]).getFormatCont()) + "|");
			}
			//拼接SQL
			if (keyStr.toString().equals("")) {
				throw new RuntimeException("没有需要保存的字段，请查看表属性配置！");
			}
			String sqlKeys = keyStr.toString().substring(0, keyStr.toString().length() - 1) + ")";
			String sqlVals = valueStr.toString().substring(0, valueStr.toString().length() - 1) + ")";
			String[] valuesArr = values.toString().split("\\|");
			String tableName = dataStore.getUpdateTable();
			String sqlText = " insert into " + tableName + sqlKeys + " values " + sqlVals;
			//执行sql
			boolean flag = frameworkService.saveObject(sqlText, valuesArr);
			returnObject.setNameValue(nameValue);
			returnObject.setInfo("Success");
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setInfo(e.getMessage());
		}
		return returnObject;
	}

	/**
	 * 返回dataGrid中的数据
	 *
	 * @param dataGParams
	 * @param dsId
	 * @param request
	 * @return
	 * @author Xuzq 2014-01-20
	 */
	@RequestMapping("/loadData")
	@ResponseBody
	public QueryJson queryPlanTopic(DataGridReceiveParams dataGParams, String dsId, String config, HttpServletRequest request, HttpSession session) {
		QueryJson queryJson = new QueryJson();
		try {
			String[] configS = null;
			if (config != null) {
				configS = config.split(";");
			}
			String[] dsIds = dsId.split(";");
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.318");
			}
			String sql = frameworkService.formatSql(dsId, dataStore.getSqlText(), uid == null ? "" : uid.toString());
			if (dataStore != null) {
				StringBuffer sqlBuffer = new StringBuffer("select * from (" + sql + ") QUERYTMP where 1 = 1  ");
				String[] tmpValue;
				if (configS != null) {
					for (int i = 0; i < configS.length; i++) {
						tmpValue = configS[i].split("\\-");
						if (tmpValue.length == 2) {
							sqlBuffer.append(" AND " + tmpValue[0] + "='" + tmpValue[1] + "' ");
						}
					}
				}
				String finalSql = sqlBuffer.toString().replace("$dsid", dsIds[0]);
				QueryJson tmpQJ = frameworkService.queryRowsBySqlPagination(finalSql, dataGParams.getPage(), dataGParams.getRows());
				queryJson.setRows(tmpQJ.getRows());
				queryJson.setTotal(tmpQJ.getTotal());
				queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}


	public StringBuffer getSql(List<String> vals, String showName, String yuanSql) {
		StringBuffer sqlStr = new StringBuffer();
		for (int i = 0; i < vals.size(); i++) {
			String newSql = yuanSql.replace("?", vals.get(i).toString().trim().toUpperCase());
			if (i == vals.size() - 1) {
				sqlStr.append(newSql);
			} else {
				sqlStr.append(newSql + " OR ");
			}
		}
		return sqlStr;
	}

	/**
	 * 返回dataGrid中的数据 V2.0.0  包含条件
	 * @param dataGParams
	 * @param dsId
	 * @param config    所有查询条件的拼接
	 * @param originalSql 是在原sql上的拼接
	 * @param charFlag  用于标识输入的字符类型
	 * @param request
	 * @param session
	 * @return
	 * @author Xuzq
	 * @date 2014-5-14 下午02:35:33
	 */
	/**
	 * *
	 * 说明：
	 * 需要转换的字符 ：
	 * eq  等于   		neq 	不等于
	 * alike 以...开头  	likea　	以...结尾    inc包含
	 * 字符串 1-  ：flag - ClnName - value1 -neq |+
	 * 间隔 2-：	   flag - clnName - Num - num2  |+
	 * 列表 3-：   flag - clnName - value1;value2 |+   //单选  编码集合 查询
	 * 时间间隔 4-:  flag - clnName- date1 - date2 |+
	 * 下拉框 3-：	flag - clnName - value |+ //同列表 支持普通单选弹窗
	 * 模糊查询对照表  5- ： flag - ClnName - editype - value1 -neq |+ //单选 或者 下拉 的模糊查询
	 * 一对多查询：6-：flag - clnName - dsid - value1;value2 |+ //一对多 编码集合 查询
	 * 一对多查询：7-：flag - clnName - dsid - Cname1;Cname2  -neq|+	//一对多的模糊查询  根据名字查询
	 * 单选查询：	 *-：flag - clnName - dsid - Cname1;Cname2 -neq |+	//根据名字查询  暂无
	 * 获取数据的时候  需要优化  特殊字符
	 * qFlag:查询的方式            空值和true：需要分页       false：是不需要分页
	 */
	//注意目前只有flagA==5和7 支持多个条件查询，其余的后期加入
	@RequestMapping("/loadDataQ")
	@ResponseBody
	public QueryJson queryRowsDG(DataGridReceiveParams dataGParams, String dsId, String config, String originalSql, String isTotal, String qFlag, String isRep, HttpServletRequest request, HttpSession session) {
		QueryJson queryJson = new QueryJson();
		try {
			String[] dsIds = dsId.split(";");
			String date1 = "";
			String date2 = "";
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.318");
			}
			String sql = frameworkService.formatSql(dsIds[0], dataStore.getSqlText(), uid == null ? "" : uid.toString());
			if (dataStore != null) {
				StringBuffer sqlBuffer = new StringBuffer();
				StringBuffer sqlBuffer1 = new StringBuffer();
				String[] tmpValue2;
				String tmpStr = "";  //缓存语句
				String tmpStr2 = ""; //缓存语句2
				String flagA = ""; //缓存标志
				String tmpName = "";//缓存 字段
				String tmpValue = "";  //缓存值
				String editype = "";//缓存editype
				String tmpDateValue = ""; 	// 缓存查询日期相关
				String tmpCustDateValue = ""; 	// 缓存查询日期相关
				String tmpCustInit1DateValue = ""; 	// 缓存查询日期相关
				String tmpCustInit2DateValue = ""; 	// 缓存查询日期相关
				String tmpClientIdValue = "";		// 缓存客户查询相关

				if (config != null && config.trim() != "") {
					String[] configS = config.split("\\|\\+");
					StringBuffer whereStr = new StringBuffer();//缓存条件语句
					for (int i = 0; i < configS.length; i++) {
						if (configS[i] != null && !"".equals(configS[i])) {
							flagA = configS[i].substring(0, 1);
							tmpStr = configS[i].substring(2, configS[i].length());
							//					*     字符串1  ：flag - ClnName - value1 -neq +
							//							eq  等于   		neq 	不等于
							//					 *      alike 以...开头  	likea　	以...结尾    inc包含
							//					 *   数值 间隔2：	 flag - date Num - value1 - value2  +
							//					 *       列表3：     flag - staId - value1;value2 +
							//					 	   时间间隔4:   flag - clnName- date1 - date2 +
							if (flagA.equals("1")) {
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")).trim();
								if ("".equals(tmpStr)) {
									continue;
								}
								//获取input框传入的参数
								String parm = tmpStr.toString().toUpperCase();
								String[] parms = parm.split(";");
								//遍历参数       对出版社简sql条件进行添加
								for (String p : parms) {
									if ("eq".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND nvl(" + tmpName + ",0) = '" + p + "' ");
											sqlBuffer1.append(" AND nvl(" + tmpName + ",0) = '" + p + "' ");
										} else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "') ");
											sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "') ");
										}
										//	sqlBuffer.append(" AND (("+tmpName+"='"+p+"') OR (upper(getch2spell(Nvl("+tmpName+",' ')))= getch2spell('"+p+"')))  ");
									} else if ("neq".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND (" + tmpName + " not in ('" + p + "'))  ");
											sqlBuffer1.append(" AND (" + tmpName + " not in ('" + p + "'))  ");
										} else {
											sqlBuffer.append(" AND  (upper(getch2spell(Nvl(" + tmpName + ",' ')))  not in getch2spell('" + p + "')) ");
											sqlBuffer1.append(" AND  (upper(getch2spell(Nvl(" + tmpName + ",' ')))  not in getch2spell('" + p + "')) ");
										}
										//sqlBuffer.append(" AND (("+tmpName+" not in ('"+p+"')) AND  upper((getch2spell(Nvl("+tmpName+",' ')))  not in getch2spell('"+p+"')))");
									} else if ("alike".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND " + tmpName + " like '" + p + "%' ");
											sqlBuffer1.append(" AND " + tmpName + " like '" + p + "%' ");
										} else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "%')  ");
											sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "%')  ");
										}
										//	sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('"+p+"%') ");
									} else if ("likea".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND " + tmpName + " like '%" + p + "'");
											sqlBuffer1.append(" AND " + tmpName + " like '%" + p + "'");
										} else {
											sqlBuffer.append("  AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "')  ");
											sqlBuffer1.append("  AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "')  ");
										}
										//sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('%"+p+"') ");
									} else if ("inc".equals(tmpStr2)) {
										//判断是不是数字
										Pattern pattern = Pattern.compile("[0-9]*");
										//判断是不是负数
										Pattern pattern2 = Pattern.compile("-?[0-9]*");
										//首先判断是否包含",",如果包含，代表是并列查询
										String[] pvals = p.split(",");
										if (pvals.length > 0) {
											//((tmpName like '%1510%') or (tmpName like '%1513%'))
											StringBuffer newSql = new StringBuffer();
											for (int j = 0; j < pvals.length; j++) {
												if (j == 0) {
													if (pvals[j].matches("^[a-zA-Z]{0,}$")) {
														newSql.append(" ( upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + pvals[j] + "%') )");

													} else if (pattern.matcher(pvals[j]).matches()) {
														newSql.append(" (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													} else if (pattern2.matcher(pvals[j]).matches()) {
														newSql.append(" (" + tmpName + " = " + pvals[j] + " ) ");
													} else {
														newSql.append(" (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													}
												} else {
													if (pvals[j].matches("^[a-zA-Z]{0,}$")) {
														newSql.append(" or ( upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + pvals[j] + "%') )");
													} else {
														newSql.append(" or (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													}
												}
											}
											sqlBuffer.append(" AND " + "(" + newSql + ")");
											sqlBuffer1.append(" AND " + "(" + newSql + ")");
										} else {
											//判断传入的参数不是英文
											if (p.matches("^[^a-zA-Z]*$")) {
												sqlBuffer.append(" AND " + tmpName + " like '%" + p + "%' ");
												sqlBuffer1.append(" AND " + tmpName + " like '%" + p + "%' ");
											} else {
												sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "%') ");
												sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "%') ");
											}
										}
									}
								}
							} else if (flagA.equals("2")) {
								//							 *    间隔2：	   flag - clnName - Num - num2  +
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								if (tmpStr.lastIndexOf("-") > tmpStr.length() + 1) {
									tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());
									sqlBuffer.append(" AND " + tmpName + " <= " + tmpStr2 + " ");
									sqlBuffer1.append(" AND " + tmpName + " <= " + tmpStr2 + " ");
								}
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-"));
								if (!"".equals(tmpStr)) {
									sqlBuffer.append(" AND " + tmpName + " >= " + tmpStr + " ");
									sqlBuffer1.append(" AND " + tmpName + " >= " + tmpStr + " ");
								}
							} else if (flagA.equals("3")) {   //3-STOCK_ID-GOM1K00000|+        3-PRINT_MAN-22378EADC22087536F54752CD5FD1CE6|+
								//							flag - staId - value1;value2 +
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());
								if ("".equals(tmpStr)) {
									continue;
								}
								tmpValue2 = tmpStr.split(";");
								tmpStr = "";
								for (int k = 0; k < tmpValue2.length; k++) {
									tmpStr += "'" + tmpValue2[k] + "'";
									if (k < tmpValue2.length - 1) {
										tmpStr += ",";
									}
								}
								sqlBuffer.append(" AND " + tmpName + " in (" + tmpStr + ")");
								sqlBuffer1.append(" AND " + tmpName + " in (" + tmpStr + ")");
							} else if (flagA.equals("4")) {
								//							时间间隔4:   flag - clnName- date1 - date2 +
								//							 input_date >  to_date('2014-5-12 00:00:00','yyyy-mm-dd hh24:mi:ss')
								//							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
								SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								String tmpStr3 = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-"));   //第一个时间框内的值
								String tmpStr21 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //第二个时间框内的值
								date1 = tmpStr3;
								date2 = tmpStr21;
								//纸张结存查询的时候条件去除时间（特殊处理）
								if (dsId.toString().equals("ds_cl_left_mx")) sqlBuffer.append(" ");
								if (dsId.toString().equals("ds_cw_klfx_mx")) sqlBuffer.append(" ");//库龄分析统计
								else if (!"".equals(tmpStr3) && !"".equals(tmpStr21) && tmpStr3.equals(tmpStr21)) {  //两个框内都有值,，并且两个值相等
									String jqDate = df.format(new Date(Long.parseLong(tmpStr3)));
									sqlBuffer.append(" AND to_char(" + tmpName + " ,'yyyy-MM-dd')  = '" + jqDate + "'");
								} else {
									if (!"".equals(tmpStr3)) {
										sqlBuffer.append(" AND to_char(" + tmpName + ",'yyyy-MM-dd') >= '" + df.format(new Date(Long.parseLong(tmpStr3))) + "'");
									}
									if (!"".equals(tmpStr21)) {
										sqlBuffer.append(" AND to_char(" + tmpName + ",'yyyy-MM-dd') <= '" + df.format(new Date(Long.parseLong(tmpStr21))) + "'");
									}
								}

								if (dsId.toString().equals("ds_fx_jsManager_MX1")) {
									if (!"".equals(tmpStr3) && !"".equals(tmpStr21) && tmpStr3.equals(tmpStr21)) {  //两个框内都有值,，并且两个值相等
										String jqDate = df.format(new Date(Long.parseLong(tmpStr3)));
										tmpDateValue = " AND to_char(" + tmpName + " ,'yyyy-MM-dd')  = '" + jqDate + "'";
										tmpCustDateValue = " AND to_char(VERIFY_DATE,'yyyy-MM-dd')  = '" + DateUtils.plusOneMonthEnd(new Date(Long.parseLong(tmpStr3)), "yyyy-MM-dd") + "'";
									} else {
										if (!"".equals(tmpStr3)) {
											tmpDateValue = " AND to_char(" + tmpName + ",'yyyy-MM-dd') >= '" + df.format(new Date(Long.parseLong(tmpStr3))) + "'";
											tmpCustDateValue = " AND to_char(VERIFY_DATE,'yyyy-MM-dd') >= '" + DateUtils.plusOneMonth(new Date(Long.parseLong(tmpStr3)), "yyyy-MM-dd") + "'";

											// 用于查询上个月的期初库存
											tmpCustInit1DateValue = " AND to_char(STOCK_DATE,'yyyy-MM-dd') <= '" + DateUtils.subtractOneDay(new Date(Long.parseLong(tmpStr3)),"yyyy-MM-dd") + "'";
											tmpCustInit2DateValue = " AND to_char(VERIFY_DATE,'yyyy-MM-dd') <= '" + DateUtils.thisMonthEnd(new Date(Long.parseLong(tmpStr3)),"yyyy-MM-dd") + "'";
										}
										if (!"".equals(tmpStr21)) {
											tmpDateValue += " AND to_char(" + tmpName + ",'yyyy-MM-dd') <= '" + df.format(new Date(Long.parseLong(tmpStr21))) + "'";
											tmpCustDateValue += " AND to_char(VERIFY_DATE,'yyyy-MM-dd') <= '" + DateUtils.plusOneMonthEnd(new Date(Long.parseLong(tmpStr21)),"yyyy-MM-dd") + "'";
										}
									}
								}
  							} else if (flagA.equals("5")) {
								//5 flag - ClnName - editype - value1 -neq |+
								if ("".equals(tmpStr)) {
									continue;
								}
								String colnName = tmpStr.substring(0, tmpStr.indexOf("-"));      //列名
								String operatorFlag = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //关系运算符
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")); //dzId-value

								//

								String dzId = tmpStr.substring(0, tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());   //输入的查询条件的字符串的
								String[] valArr1 = valueStr.split(";");  //前台输入的谐音数组 NAME = CL;JK;KL;
								//								List<String> vals=new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								//								for (int j = 0; j < valArr1.length; j++) {
								//									if(valArr1[j]!=null&&valArr1[j]!=""){
								//										vals.add(valArr1[j]);
								//									}
								//								}
								String sqlForText = "select sql_text,show_pk,show_name from sys_dz_source c where c.dz_id ='" + dzId + "'";
								SysDzSource dzSource = (SysDzSource) frameworkService.sqlForList(sqlForText);
								String showName = dzSource.getShowName();
								String showPk = dzSource.getShowPk();
								String sqlText = dzSource.getSqlText();

								//								StringBuffer configSql = new StringBuffer();
								//								configSql.append(" AND ");

								String sqlConfig = " AND";
								for (int n = 0; n < valArr1.length; n++) {
									String p = valArr1[n];
									if ("eq".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' ')))= getch2spell(Nvl('" + p.trim().toUpperCase() + "',''))  ";
										} else {
											sqlConfig += " (" + showName + "='" + p + "')";
										}
									} else if ("neq".equals(operatorFlag)) {
										sqlConfig += "(" + showName + " not in ('" + p + "')) ";
									} else if ("alike".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " nvl(" + showName + ",' ') like '" + p + "%'";
										}
									} else if ("likea".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "')";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "'";
										}
									} else if ("inc".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "%'";
										}
									}
									if (n < valArr1.length - 1) {
										sqlConfig = sqlConfig + " OR";
									}
									//拼接条件
									//									configSql.append(getSql(vals,showName,sqlConfig));
								}
								//得到前台输入的条件的编码的集合
								//								String tmpSql = " select  "+showPk +" from ("+ sqlText+") A where 1=1 "+configSql;
								String tmpSql = " select  " + showPk + " from (" + sqlText + ") A where 1=1 " + sqlConfig;
								List<Map<String, String>> idList = frameworkService.execSql(tmpSql);

								StringBuffer likestr = new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append(colnName + " like '%" + idList.get(j).get(dzSource.getShowPk()) + "%'");
										if (j < (idList.size() - 1)) {
											likestr.append(" or ");
										}
									}
									sqlBuffer.append(" AND (" + likestr + ") ");
									sqlBuffer1.append(" AND (" + likestr + ") ");
								} else {
									sqlBuffer.append(" AND (0=1) ");
									sqlBuffer1.append(" AND (0=1) ");
								}

								// report-结算客户月进销存
								if ("ds_fx_jsManager_MX1".equalsIgnoreCase(dsId) && "CLIENT_ID".equalsIgnoreCase(colnName)) {
									tmpClientIdValue = " AND " + likestr + " ";
								}

							} else if (flagA.equals("6")) {    //一对多根据ID查
								//							flag - clnName - dsid - value1;value2 +
								//根据dsid 和 name 查找对应的表  及对应的字段、
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());
								String dsid = tmpStr.substring(0, tmpStr.indexOf("-"));
								//查找出包含的所有的字段
								//只查询mul的四个字段
								//MULTI_CLNS_TABLE,MULTI_CLNS_FK,MULTI_CLNS_VALUE,MULTI_DZ_DS_ID
								SysColumns tmpOnly4P = this.frameworkService.queryColumnsMul(dsid, clnName);
								//select distinct sin_id where mul_id in (ids);
								//								sql语句 本字段   包含在这里面
								String[] idsArr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length()).split(";");
								StringBuffer tmpIds = new StringBuffer();
								//								V1.0.1
								//								for(int k = 0; k < idsArr.length; k ++){
								//									tmpIds.append("'"+idsArr[k]+"'");
								//									if (k < idsArr.length - 1) {
								//										tmpIds.append(",");
								//									}
								//								}
								//								v2.0
								for (int k = 0; k < idsArr.length; k++) {
									tmpIds.append(clnName + " LIKE '%" + idsArr[k] + "%' ");
									if (k < idsArr.length - 1) {
										tmpIds.append(" OR ");
									}
								}

								//			" AND SIN_ID IN (select distinct sin_id where mul_id in (ids))
								tmpStr = " select distinct " + tmpOnly4P.getMultiClnsFk()
										+ " from " + tmpOnly4P.getMultiClnsTable()
										+ " where " + tmpOnly4P.getMultiClnsDValue() + " in ("
										+ tmpIds + ")";
								//								sqlBuffer.append(" AND "+clnName+" in ("+tmpStr+")"); //v1.0.1
								sqlBuffer.append(" AND (" + tmpIds + ")"); //v2.0.0
								sqlBuffer1.append(" AND (" + tmpIds + ")"); //v2.0.0
							}
							//一对多的模糊查询(flag - clnName - dsid - value1;value2 -neq +)
							else if (flagA.equals("7")) {
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-")); //列名
								String operatorFlag = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //关系运算符
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")); //dzId-value
								String dzId = tmpStr.substring(0, tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());   //输入查询条件字符串
								String[] valArr1 = valueStr.split(";");  //字符串分割的谐音数组
								List<String> vals = new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								for (int j = 0; j < valArr1.length; j++) {
									if (valArr1[j] != null && valArr1[j] != "") {
										vals.add(valArr1[j]);
									}
								}
								//根据dsId，和列名查询该列一对多的的配置信息
								SysColumns mulObj = this.frameworkService.queryColumnsMul(dsId, clnName);
								SysDzSource dzSource = this.frameworkService.loadDzSource(dzId);
								if (dzSource == null) {
									throw new RuntimeException("找不到对照信息[" + mulObj.getEditypeQr() + "]用于条件查询");
								}
								String showName = dzSource.getShowName();
								String showPk = dzSource.getShowPk();
								StringBuffer sqlText = new StringBuffer(dzSource.getSqlText());

								String sqlConfig = " AND";
								for (int n = 0; n < valArr1.length; n++) {
									String p = valArr1[n];
									if ("eq".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' ')))= getch2spell(Nvl('" + p.trim().toUpperCase() + "',''))  ";
										} else {
											sqlConfig += " (" + showName + "='" + p + "')";
										}
									} else if ("neq".equals(operatorFlag)) {
										sqlConfig += "(" + showName + " not in ('" + p + "')) ";
									} else if ("alike".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " nvl(" + showName + ",' ') like '" + p + "%'";
										}
									} else if ("likea".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "')";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "'";
										}
									} else if ("inc".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "%'";
										}
									}
									if (n < valArr1.length - 1) {
										sqlConfig = sqlConfig + " OR";
									}
								}
								String tmpSql = " select  " + showPk + " from (" + sqlText + ") A where 1=1 " + sqlConfig;
								//获取编码的集合
								List<Map<String, String>> idList = frameworkService.execSql(tmpSql);
								StringBuffer likestr = new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append(clnName + " like '%" + idList.get(j).get(showPk) + "%'");
										if (j < (idList.size() - 1)) {
											likestr.append(" or ");
										}
									}
									sqlBuffer.append(" AND (" + likestr + ") ");
									sqlBuffer1.append(" AND (" + likestr + ") ");
								} else {
									sqlBuffer.append(" AND (0=1) ");
									sqlBuffer1.append(" AND (0=1) ");
								}
							} else {
								throw new RuntimeException("查询条件传入有误,没有按照相关规则,请联系开发调试");
							}
						}
					}
				}

				StringBuffer finalSql = new StringBuffer("select * from (" + sql + ") QUERYTMP where 1 = 1  ");
				//拼接页面的查询条件sql(排除报表，所有的报表用'AINIT'='AINIT' 替换查询条件)
				if (!"true".equals(isRep)) {
					finalSql.append(sqlBuffer);
				}
				//拼接数据权限sql
				String conditionSql = frameworkService.queryConditionSql(dsId, uid.toString());


				String QcDataParam = "'STOCKDATE'='STOCKDATE'";
				if (finalSql.toString().indexOf(QcDataParam) > 0) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1)) && (!"".equals(date2))) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = " to_char(IMPORT_DATEM, 'yyyy-MM-dd') >= '" + jqDate + "' and  to_char(IMPORT_DATEM, 'yyyy-MM-dd') <= '" + jqDate1 + "'";
					} else if (!"".equals(date1)) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						qcDate = " to_char(IMPORT_DATEM, 'yyyy-MM-dd') >= '" + jqDate + "'";
					} else if(!"".equals(date2)) {
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = " and  to_char(IMPORT_DATEM, 'yyyy-MM-dd') <= '" + jqDate1 + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam, qcDate));
					}
				}
				String QcDataParam2 = "QCDATE=QCDATE";
				if (finalSql.toString().indexOf(QcDataParam2) > 0) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1)) && (!"".equals(date2))) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = jqDate + '#' + jqDate1;
					}
					finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam2, qcDate));
				}

				String QcDataParam3 = "'XSINFO'='XSINFO'";
				if (finalSql.toString().indexOf(QcDataParam3) > 0 && !sqlBuffer.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer = new StringBuffer(sqlBuffer.toString().replaceFirst("AND", " "));
					if (sqlBuffer.indexOf("STOCK_DATE") != -1 && sqlBuffer.indexOf("CLIENT_ID") != -1) {
						sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 12)));
					}
					if (sqlBuffer.indexOf("STOCK_DATE") != -1 && sqlBuffer.indexOf("CLIENT_ID") == -1) {
						if(sqlBuffer.indexOf("H_NAME") != -1) {
							sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 12)));
							finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, sqlBuffer));
						} else {
							sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 11)));
							finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, "1=1"+sqlBuffer));
						}
					}
					finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, sqlBuffer));
					System.out.println("======================#FrameworkController 750  查询生成的SQL语句" + finalSql);
				}

				String QcDataParam4 = "'ONEDATE'='ONEDATE'";
				if (finalSql.toString().indexOf(QcDataParam4) > 0 && !sqlBuffer.toString().trim().equals("")) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1))) {
						String jqDate = "";
						Calendar ca = Calendar.getInstance();
						ca.setTime(new Date(Long.parseLong(date1)));
						ca.set(Calendar.DAY_OF_MONTH, 1);
						ca.add(Calendar.DATE, -1);
						jqDate = (new SimpleDateFormat("yyyy-MM-dd")).format(ca.getTime());

						qcDate = " to_char(CE.DATES, 'yyyy-MM-dd') <= '" + jqDate + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam4, qcDate));
					}
				}


				String QcDataParam5 = "'TWODATE'='TWODATE'";
				if (finalSql.toString().indexOf(QcDataParam5) > 0 && !sqlBuffer.toString().trim().equals("")) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date2))) {
						String jqDate = "";
						Calendar ca = Calendar.getInstance();
						ca.setTime(new Date(Long.parseLong(date2)));
						ca.set(Calendar.DAY_OF_MONTH,
								ca.getActualMaximum(Calendar.DAY_OF_MONTH));
						jqDate = (new SimpleDateFormat("yyyy-MM-dd")).format(ca.getTime());

						qcDate = " to_char(CE.DATES, 'yyyy-MM-dd') <= '" + jqDate + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam5, qcDate));
					}
				}
				/**
				 * 纸张结存统计
				 */
				if (finalSql.toString().contains("$ASE$")) {
					finalSql = new StringBuffer(finalSql.toString().replace("$ASE$", ""));
					String sp1 = "$AS_DATE";//期初
					String sp2 = "$AE_DATE";//期末
					String sp3 = "$CSE_DATE";//本期

					String sp4 = "$GP_DATES";//分组日期
					if (StringUtils.isNotBlank(date1) && StringUtils.isNotBlank(date2)) {
						finalSql = new StringBuffer(finalSql.toString().replace(sp4, ""));

						//纸张结存统计
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));

						String qcDate = "";
						/**
						 * 期初
						 */
						if (finalSql.toString().contains(sp1)) {
//                            qcDate = " AND STOCK_DATE < trunc(to_date('"+jqDate+"','yyyy-MM-dd'),'mm')";

							qcDate = " AND STOCK_DATE < to_date(to_char(to_date('" + jqDate + "','YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD') || ' 00:00:00','YYYY-MM-DD HH24:MI:SS')";
							finalSql = new StringBuffer(finalSql.toString().replace(sp1, qcDate));
						} else {
							finalSql = new StringBuffer(finalSql.toString().replace(sp1, ""));
						}
						/**
						 * 本期
						 */
						if (finalSql.toString().contains(sp3)) {
							qcDate = " AND STOCK_DATE >= to_date(to_char(to_date('" + jqDate + "','YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD') || ' 00:00:00','YYYY-MM-DD HH24:MI:SS') and  STOCK_DATE <= to_date(to_char(to_date('" + jqDate1 + "','YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD') || ' 23:59:59','YYYY-MM-DD HH24:MI:SS')";
							finalSql = new StringBuffer(finalSql.toString().replace(sp3, qcDate));
						} else {
							finalSql = new StringBuffer(finalSql.toString().replace(sp3, ""));
						}

						/**
						 * 期末
						 */
						if (finalSql.toString().contains(sp2)) {
							qcDate = " AND STOCK_DATE <= to_date(to_char(to_date('" + jqDate1 + "','YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD') || ' 23:59:59','YYYY-MM-DD HH24:MI:SS')";
							finalSql = new StringBuffer(finalSql.toString().replace(sp2, qcDate));
						} else {
							finalSql = new StringBuffer(finalSql.toString().replace(sp2, ""));
						}
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(sp1, " AND STOCK_DATE < CE.STOCK_DATE "));
						finalSql = new StringBuffer(finalSql.toString().replace(sp3, " AND STOCK_DATE = CE.STOCK_DATE"));
						finalSql = new StringBuffer(finalSql.toString().replace(sp2, " AND STOCK_DATE <= CE.STOCK_DATE "));

						finalSql = new StringBuffer(finalSql.toString().replace(sp4, ",CE.STOCK_DATE "));

					}
				}

				/**
				 * 库龄分析统计
				 */
				if (finalSql.toString().contains("$KLFX$")) {
					finalSql = new StringBuffer(finalSql.toString().replace("$KLFX$", ""));
					String sp2 = "$YEAR2";//2012年数据
					String sp3 = "$YEAR3";//2013年数据
					String sp4 = "$YEAR4";//2014年数据
					String sp5 = "$YEAR5";//2015年数据
					String sp6 = "$YEAR6";//2016年数据
					String sp7 = "$YEAR7";//2017年数据
//                    String kcamount = "$KCA";//库存数量
					String rkamount = "$RKA";//入库数量
					String rkdate = "$RKDATE";//入库时间

					String st2 = "$2";//2012年数据
					String st3 = "$3";//2013年数据
					String st4 = "$4";//2014年数据
					String st5 = "$5";//2015年数据
					String st6 = "$6";//2016年数据
					String st7 = "$7";//2017年数据

					if (StringUtils.isNotBlank(date1) && StringUtils.isNotBlank(date2)) {
						//库龄分析统计
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						Date dt1 = df.parse(jqDate);
						Date dt2 = df.parse(jqDate1);
						String qcDate = "";
						/**
						 * 2012年数据
						 */
						if (finalSql.toString().contains(sp2)) {
							Date dt12 = df.parse("2012-01-01");
							Date dt22 = df.parse("2012-12-31");
							finalSql = new StringBuffer(finalSql.toString().replace(st2, "1"));
							if (dt1.getTime() >= dt12.getTime() && dt1.getTime() <= dt22.getTime()) {//假设时间在2012之间/* 这里的qcDate还是有问题的*/
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2012-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp2, qcDate));
							} else {//下面这种情况是时间超过了2012年
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2012-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2012-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp2, qcDate));
							}

						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st2, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp2, ""));
						}
						/**
						 * 2013年数据
						 */
						if (finalSql.toString().contains(sp3)) {
							Date dt13 = df.parse("2013-01-01");
							Date dt23 = df.parse("2013-12-31");
							if (dt1.getTime() < dt13.getTime()) {//假设时间是2012年那么就没有时间
								//可以在这里写一个替代导致查询不出2013年数据即可,在这里的2 是因为sql中where 1=$3
								finalSql = new StringBuffer(finalSql.toString().replace(st3, "2"));
								finalSql = new StringBuffer(finalSql.toString().replace(sp3, ""));
							} else if (dt1.getTime() >= dt13.getTime() && dt1.getTime() <= dt23.getTime()) {//假设时间在2013之间那么就是它本身的时间
								finalSql = new StringBuffer(finalSql.toString().replace(st3, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2013-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp3, qcDate));
							} else {//假设时间超过2013年那么时间就是2013-01-01到2013-12-31
								finalSql = new StringBuffer(finalSql.toString().replace(st3, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2013-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2013-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp3, qcDate));
							}
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st3, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp3, ""));
						}

						/**
						 * 2014年数据
						 */
						if (finalSql.toString().contains(sp4)) {
							Date dt14 = df.parse("2014-01-01");
							Date dt24 = df.parse("2014-12-31");
							if (dt1.getTime() < dt14.getTime()) {//假设时间是2013年那么就没有时间
								//可以在这里写一个替代导致查询不出2014年数据即可,在这里的2 是因为sql中where 1=$3
								finalSql = new StringBuffer(finalSql.toString().replace(st4, "2"));
								finalSql = new StringBuffer(finalSql.toString().replace(sp4, ""));
							} else if (dt1.getTime() >= dt14.getTime() && dt1.getTime() <= dt24.getTime()) {//假设时间在2014之间那么就是它本身的时间
								finalSql = new StringBuffer(finalSql.toString().replace(st4, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2014-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp4, qcDate));
							} else {//假设时间超过2014年那么时间就是2014-01-01到2014-12-31
								finalSql = new StringBuffer(finalSql.toString().replace(st4, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2014-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2014-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp4, qcDate));
							}
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st4, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp4, ""));
						}
						/**
						 * 2015年数据
						 */
						if (finalSql.toString().contains(sp5)) {
							Date dt15 = df.parse("2015-01-01");
							Date dt25 = df.parse("2015-12-31");
							if (dt1.getTime() < dt15.getTime()) {//假设时间是2014年那么就没有时间
								//可以在这里写一个替代导致查询不出2015年数据即可,在这里的2 是因为sql中where 1=$3
								finalSql = new StringBuffer(finalSql.toString().replace(st5, "2"));
								finalSql = new StringBuffer(finalSql.toString().replace(sp5, ""));
							} else if (dt1.getTime() >= dt15.getTime() && dt1.getTime() <= dt25.getTime()) {//假设时间在2015之间那么就是它本身的时间
								finalSql = new StringBuffer(finalSql.toString().replace(st5, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2015-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp5, qcDate));
							} else {//假设时间超过2015年那么时间就是2015-01-01到2015-12-31
								finalSql = new StringBuffer(finalSql.toString().replace(st5, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2015-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2015-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp5, qcDate));
							}
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st5, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp5, ""));
						}


						/**
						 * 2016年数据
						 */
						if (finalSql.toString().contains(sp6)) {
							Date dt16 = df.parse("2016-01-01");
							Date dt26 = df.parse("2016-12-31");
							if (dt1.getTime() < dt16.getTime()) {//假设时间是2015年那么就没有时间
								//可以在这里写一个替代导致查询不出2016年数据即可,在这里的2 是因为sql中where 1=$3
								finalSql = new StringBuffer(finalSql.toString().replace(sp6, ""));
								finalSql = new StringBuffer(finalSql.toString().replace(st6, "2"));
							} else if (dt1.getTime() >= dt16.getTime() && dt1.getTime() <= dt26.getTime()) {//假设时间在2016之间那么就是它本身的时间
								finalSql = new StringBuffer(finalSql.toString().replace(st6, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2016-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp6, qcDate));
							} else {//假设时间超过2016年那么时间就是2016-01-01到2016-12-31
								finalSql = new StringBuffer(finalSql.toString().replace(st6, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2016-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2016-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp6, qcDate));
							}
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st6, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp6, ""));
						}
						/**
						 * 2017年数据
						 */
						if (finalSql.toString().contains(sp7)) {
							Date dt17 = df.parse("2017-01-01");
							Date dt27 = df.parse("2017-12-31");
							if (dt1.getTime() < dt17.getTime()) {//假设时间是2016年那么就没有时间
								//可以在这里写一个替代导致查询不出2017年数据即可,在这里的2 是因为sql中where 1=$3
								finalSql = new StringBuffer(finalSql.toString().replace(st7, "2"));
								finalSql = new StringBuffer(finalSql.toString().replace(sp7, ""));
							} else if (dt1.getTime() >= dt17.getTime() && dt1.getTime() <= dt27.getTime()) {//假设时间在2017之间那么就是它本身的时间
								finalSql = new StringBuffer(finalSql.toString().replace(st7, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2017-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('" + jqDate + "', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp7, qcDate));
							} else {//假设时间超过2017年那么时间就是2017-01-01到2017-12-31
								finalSql = new StringBuffer(finalSql.toString().replace(st7, "1"));
								qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2017-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('2017-12-31', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
								finalSql = new StringBuffer(finalSql.toString().replace(sp7, qcDate));
							}
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(st7, "2"));
							finalSql = new StringBuffer(finalSql.toString().replace(sp7, ""));
						}
						/**
						 * 库存数量
						 */
                        /*if (finalSql.toString().contains(kcamount)) {
                                qcDate = " AND TO_CHAR(KCDATE, 'yyyy-mm-dd')='"+jqDate+"' ";
                                finalSql = new StringBuffer(finalSql.toString().replace(kcamount, qcDate));
                        } else {//在这个功能里是必须要有时间的，所以这个esle是没用的
                            finalSql = new StringBuffer(finalSql.toString().replace(kcamount, ""));
                        }*/

						/**
						 * 入库数量
						 */
						if (finalSql.toString().contains(rkamount)) {
							//假设时间超过2017年那么时间就是2017-01-01到2017-12-31
							qcDate = " AND to_char(VK.STOCK_DATE, 'YYYY-MM-DD') BETWEEN to_char(to_date('2012-01-01', 'yyyy-mm-dd'), 'yyyy-mm-dd') AND to_char(to_date('"+jqDate+"', 'yyyy-mm-dd'), 'yyyy-mm-dd')";
							finalSql = new StringBuffer(finalSql.toString().replace(rkamount, qcDate));
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(rkamount, ""));
						}
						/**
						 * 时间
						 */
						if (finalSql.toString().contains(rkdate)) {
							qcDate = "'"+jqDate+"'";
							finalSql = new StringBuffer(finalSql.toString().replace(rkdate, qcDate));
						} else {//在这个功能里是必须要有时间的，所以这个esle是没用的
							finalSql = new StringBuffer(finalSql.toString().replace(rkdate, ""));
						}

					} else {
						//这里是没有时间的时候进入
						finalSql = new StringBuffer(finalSql.toString().replace(st2, "2"));
						finalSql = new StringBuffer(finalSql.toString().replace(st3, "2"));
						finalSql = new StringBuffer(finalSql.toString().replace(st4, "2"));
						finalSql = new StringBuffer(finalSql.toString().replace(st5, "2"));
						finalSql = new StringBuffer(finalSql.toString().replace(st6, "2"));
						finalSql = new StringBuffer(finalSql.toString().replace(st7, "2"));

						finalSql = new StringBuffer(finalSql.toString().replace(sp2, ""));
						finalSql = new StringBuffer(finalSql.toString().replace(sp3, ""));
						finalSql = new StringBuffer(finalSql.toString().replace(sp4, ""));
						finalSql = new StringBuffer(finalSql.toString().replace(sp5, ""));
						finalSql = new StringBuffer(finalSql.toString().replace(sp6, ""));
						finalSql = new StringBuffer(finalSql.toString().replace(sp7, ""));
					}
				}
				/***
				 * 如果sql语句总拼接了'RIGHTSQL'='RIGHTSQL' 那么此时就把权限对应的sql语句拼接到此位置
				 */
				String rightParam = "'RIGHTSQL'='RIGHTSQL'";
				if (finalSql.toString().indexOf(rightParam) > 0 && conditionSql != null && !"".equals(conditionSql.trim())) {
					//把sqlBuffer的and 去掉
					conditionSql = conditionSql.toString().replaceFirst("and", " ");
					finalSql = new StringBuffer(finalSql.toString().replace(rightParam, conditionSql));
				} else {
					if (conditionSql != null) {
						finalSql.append(conditionSql);
					}
				}
				//sql中替换掉$dsid
				finalSql.toString().replace("$dsid", dsIds[0]);

				String chanParam6 = "'AINIT1'='AINIT1'";
				if (finalSql.toString().indexOf(chanParam6) > 0 && !sqlBuffer1.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer1 = new StringBuffer(sqlBuffer1.toString().replaceFirst("AND", " "));
					finalSql = new StringBuffer(finalSql.toString().replace(chanParam6, sqlBuffer1));
				}

				//'AINIT1_ds_fx_jsManager_MX1'='AINIT1_ds_fx_jsManager_MX1'
				String chanParam66 = "'AINIT1_ds_fx_jsManager_MX1'='AINIT1_ds_fx_jsManager_MX1'";
				if (finalSql.toString().indexOf(chanParam66) > 0 ) {
					// && !sqlBuffer1.toString().trim().equals("")
					if (StringUtils.isNotEmpty(sqlBuffer1.toString().trim())) {
						//把sqlBuffer的and 去掉
						sqlBuffer1 = new StringBuffer(sqlBuffer1.toString().replaceFirst("AND", " "));
						sqlBuffer1 = new StringBuffer(sqlBuffer1.toString().replaceAll("CLIENT_ID", "nvl(vcs.CLIENTS_ID, vsell.CLIENTS_ID)"));
						sqlBuffer1 = new StringBuffer(sqlBuffer1.toString().replaceAll("H_NAME", "vcs.H_NAME"));
						finalSql = new StringBuffer(finalSql.toString().replace(chanParam66, sqlBuffer1));
					}

					// 销售消退-果麦的销售数量
					if (StringUtils.isNotEmpty(tmpDateValue.trim())) {
						tmpDateValue = tmpDateValue.replaceFirst("AND", " ");
						if (StringUtils.isNotEmpty(tmpClientIdValue.trim())) {
							tmpDateValue += tmpClientIdValue.replace("CLIENT_ID", "XX.CLIENTS_ID");
						}

						finalSql = new StringBuffer(finalSql.toString().replace("'STOCK_DATE_ds_fx_jsManager_MX1'='STOCK_DATE_ds_fx_jsManager_MX1'", tmpDateValue));
					}

					// 批销收款进度-客户那边的销售数量
					if (StringUtils.isNotEmpty(tmpCustDateValue.trim())) {
						// tmpCustDateValue
						tmpCustDateValue = tmpCustDateValue.replaceFirst("AND", " ");
						if (StringUtils.isNotEmpty(tmpClientIdValue.trim())) {
							tmpCustDateValue += tmpClientIdValue.replace("CLIENT_ID", "VG.CLIENTS_ID");
						}

						finalSql = new StringBuffer(finalSql.toString().replace("'VERIFY_DATE_ds_fx_jsManager_MX1'='VERIFY_DATE_ds_fx_jsManager_MX1'", tmpCustDateValue));
					}

					if (StringUtils.isNotEmpty(tmpCustInit1DateValue.trim())) {
						tmpCustInit1DateValue = tmpCustInit1DateValue.replaceFirst("AND", " ");
						if (StringUtils.isNotEmpty(tmpClientIdValue.trim())) {
							tmpCustInit1DateValue += tmpClientIdValue.replace("CLIENT_ID", "XX.CLIENTS_ID");
						}

						finalSql = new StringBuffer(finalSql.toString().replace("'STOCK_DATE_INIT_ds_fx_jsManager_MX1'='STOCK_DATE_INIT_ds_fx_jsManager_MX1'", tmpCustInit1DateValue));
					}

					if (StringUtils.isNotEmpty(tmpCustInit2DateValue.trim())) {
						tmpCustInit2DateValue = tmpCustInit2DateValue.replaceFirst("AND", " ");
						if (StringUtils.isNotEmpty(tmpClientIdValue.trim())) {
							tmpCustInit2DateValue += tmpClientIdValue.replace("CLIENT_ID", "VG.CLIENTS_ID");
						}

						finalSql = new StringBuffer(finalSql.toString().replace("'VERIFY_DATE_INIT_ds_fx_jsManager_MX1'='VERIFY_DATE_INIT_ds_fx_jsManager_MX1'", tmpCustInit2DateValue));
					}

				}

				// 如果sql语句中包含AINIT' = 'AINIT 那么该字符串用查询条件替换掉sqlBuffer
				String chanParam = "'AINIT'='AINIT'";
				if (finalSql.toString().indexOf(chanParam) > 0 && !sqlBuffer.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer = new StringBuffer(sqlBuffer.toString().replaceFirst("AND", " "));
					finalSql = new StringBuffer(finalSql.toString().replace(chanParam, sqlBuffer));
				}

				final String DS_ID = "ds_jmjxctj_pz";
				final String SPLIT = "VV_FX_JMJXCTJ";
				if (DS_ID.equalsIgnoreCase(dsId)) {
					String[] tmpSql = finalSql.toString().split(SPLIT);
					finalSql = new StringBuffer();
					finalSql.append(tmpSql[0].replace("INPUT_DATE", "FR.INPUT_DATE"));
					finalSql.append(" ").append(SPLIT).append(" ");
					finalSql.append(tmpSql[1]);
				}

				if ("ds_fx_SxManager_MX1".equalsIgnoreCase(dsId)) {

					finalSql = new StringBuffer(finalSql.toString().replace("IMPORT_DATEM", "IMPORT_DATE"));
					int first = finalSql.indexOf("IMPORT_DATE");
					int leg = "IMPORT_DATE".length();
					finalSql = finalSql.replace(first, first+leg, "STOCK_DATE");
					first = finalSql.indexOf("IMPORT_DATE");
					finalSql = finalSql.replace(first, first+leg, "STOCK_DATE");

					String maxDate = "'MAXDATE'='MAXDATE'";
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
					String max = format.format(new Date(Long.parseLong(date2)));
					finalSql = new StringBuffer(finalSql.toString().replace(maxDate, "to_char(IMPORT_DATE, 'yyyy-MM')='"+max+"'"));

					String qcDate = "'QCDATE'='QCDATE'";
					SimpleDateFormat qcFmt = new SimpleDateFormat("yyyy-MM");
					String qc = qcFmt.format(new Date(Long.parseLong(date1)));
					finalSql = new StringBuffer(finalSql.toString().replace(qcDate, "to_char(DATA_MONTH, 'yyyy-MM')='"+qc+"'"));

					String[] tmp = finalSql.toString().split("--WHERE--");
					finalSql = new StringBuffer().append(tmp[0]).append(tmp[1].replace("CLIENT_ID", "VCP.CLIENT_ID")).append(tmp[2]);


					StringBuffer totalSql = new StringBuffer();
					totalSql.append("select count(*) ");
					totalSql.append(finalSql.toString().split("--TOTAL--")[1]);

					finalSql = new StringBuffer(finalSql.substring(finalSql.indexOf("select t2"), finalSql.lastIndexOf("t2")+2));

					if ("true".equals(isTotal)) {   //分页但是需要统计全部的数据
						List footRows = totalData(dsId, finalSql.toString());
						if (footRows != null && footRows.size() > 0) {
							queryJson.setFooter(footRows);
						}
					}

					int total = frameworkService.getCntBySql(totalSql.toString());

					if(StringUtils.isBlank(date2)) {
						date2 = String.valueOf(new Date().getTime());
					}

					Pagination p = new Pagination();
					p.setCurrentPage(dataGParams.getPage());
					p.setNumPerPage(dataGParams.getRows());
					p.setTotalRows(total);
					p.setTotalPages();
					//计算起始行数
					p.setStartIndex();
					//计算结束行数
					p.setLastIndex();

					StringBuffer paginationSQL = new StringBuffer("");
					paginationSQL.append(" SELECT * FROM ( ");
					paginationSQL.append(" SELECT temp.* ,ROWNUM num FROM ( ");
					paginationSQL.append(finalSql);
					paginationSQL.append(" ) temp ");
					paginationSQL.append(" ) WHERE   num <= " + p.getLastIndex()+" and 　num > " + p.getStartIndex());

					List rows = frameworkService.execSql(paginationSQL.toString());
					queryJson.setRows(rows == null ? new ArrayList() : rows);
					queryJson.setTotal(total);
					queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
					return queryJson;
				}

				originalSql = originalSql == null ? "" : originalSql;
				finalSql = finalSql.append(originalSql);

				//全结果集排序
				String sort = request.getParameter("sort");
				String order = request.getParameter("order");
				if(StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
					finalSql = finalSql.append(" ORDER BY ").append(sort).append(" ").append(order);
				}

				System.out.println("======================#FrameworkController 750  查询生成的SQL语句" + finalSql);

				//判断是否需要分页查询
				if ("false".equals(qFlag)) {   //不需要分页
					List rows = frameworkService.execSql(finalSql.toString());
					queryJson.setRows(rows == null ? new ArrayList() : rows);
					List footRows = totalData(dsId, finalSql.toString());
					if (footRows != null && footRows.size() > 0) {
						queryJson.setFooter(footRows);
					}
					queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
				} else {
					if ("true".equals(isTotal)) {   //分页但是需要统计全部的数据
						List footRows = totalData(dsId, finalSql.toString());
						if (footRows != null && footRows.size() > 0) {
							queryJson.setFooter(footRows);
						}
					}
					QueryJson tmpQJ = frameworkService.queryRowsBySqlPagination(finalSql.toString(), dataGParams.getPage(), dataGParams.getRows());
					queryJson.setRows(tmpQJ.getRows() == null ? new ArrayList() : tmpQJ.getRows());
					queryJson.setTotal(tmpQJ.getTotal());
					queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}


	/**
	 * ****************
	 * 报表   合并统计数据
	 *
	 * @param
	 * @return
	 * @throws Exception
	 */
	public List totalData(String dsId, String totalSql) throws Exception {
		List listFooter = new ArrayList();
		Map<String, String> maps = new HashMap<String, String>();
		String[] dsIds = dsId.split(";");
		String sql = "";
		if (dsIds.length > 1) {
			sql = "SELECT s.java_property_recorded,s.total_sql FROM sys_columns s WHERE s.ds_id in('" + dsIds[0] + "','" + dsIds[1] + "') AND  s.istotal='T'";
		} else {
			sql = "SELECT s.java_property_recorded,s.total_sql FROM sys_columns s WHERE s.ds_id in('" + dsId + "') AND  s.istotal='T'";
		}
		List list = frameworkService.execSql(sql);
		if (list == null || list.size() == 0) {
			return null;
		}
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				String totalFunc = "sum";
				if (map.get("TOTAL_SQL") != null && !("").equals(map.get("TOTAL_SQL"))) {
					totalFunc = (String) map.get("TOTAL_SQL");
				}
				maps.put(map.get("java_property_recorded").toString(), totalFunc);

			}
			String sqlStr = " ";
			int index = 0;
			for (String key : maps.keySet()) {
				if (index != 0) {
					sqlStr += " ," + maps.get(key) + "(" + key + ") " + key + " ";
				} else {
					sqlStr += " " + maps.get(key) + "(" + key + ") " + key + " ";
				}
				index++;
			}
			totalSql = "select " + sqlStr + " from (" + totalSql + ")";
			System.out.println("======================#FrameworkController 750  查询生成的统计语句sql" + totalSql);
			listFooter = frameworkService.execSql(totalSql);
		}
		return listFooter;
	}


	/**
	 * 返回某行记录
	 *
	 * @param
	 * @param dsId
	 * @param config
	 * @param request
	 * @return
	 * @author Xuzq
	 * @date 2014-2-25 下午05:14:27
	 */
	@RequestMapping("/loadRowData")
	@ResponseBody
	public Object queryRowData(String dsId, String config, HttpServletRequest request, HttpSession session) {
		QueryJson queryJson = null;
		Object reobj = null;
		try {
			String[] configS = config.split(";");

			DataStore dataStore = frameworkService.getDataStoreById(dsId);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.354");
			}
			String sql = frameworkService.formatRowSql(dsId, dataStore.getSqlText(), uid == null ? "" : uid.toString());
			if (dataStore != null) {
				StringBuffer sqlBuffer = new StringBuffer("select * from (" + dataStore.getSqlText() + ") QUERYTMP where 1 = 1  ");
				String[] tmpValue;
				for (int i = 0; i < configS.length; i++) {
					tmpValue = configS[i].split("\\-");
					if (tmpValue.length == 2) {
						sqlBuffer.append(" AND " + tmpValue[0] + "='" + tmpValue[1] + "' ");
					}
				}
				queryJson = frameworkService.queryRowsBySqlPagination(sqlBuffer.toString(), 1, 1);
				if (queryJson.getRows() != null && queryJson.getRows().size() > 0) {
					reobj = queryJson.getRows().get(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reobj;
	}


	//更新数据
	//@RequestMapping("updateInfo")
	//@ResponseBody
	public ReturnObject updateButClick(ReceiveParam params, String dsId, String colId, HttpServletRequest request) {
		//3.获取所有字段
		//4.将传入的参数和所有字段比较
		//5.拼接保存sql语句    （加上主键-获取主键生成方式）
		ReturnObject returnObject = new ReturnObject();
		try {
			//1.判断按钮权限

			//2.获取ds所更新的表
			//3.获取所有字段
			//     a.取出主键  设置主键值
			//     b.将界面字段遍历  所有的字段  有则留  添加到相应的字段

			DataStore dataStore = frameworkService.getDataStoreById(dsId); //获得Datastore
			List<SysColumns> cpColumns = frameworkService.colList(colId, "");//获得全部的Columns
			Map<String, SysColumns> colnMap = new HashMap<String, SysColumns>();//数据库中有属性、可更新字段
			Map<String, SysColumns> readOnlyColnMap = new HashMap<String, SysColumns>();//数据库中不可更新字段
			String[] paramsKandV = params.getSqlParams();//界面参数
			//a.取出部不可更新、可更新的字段
			for (int i = 0; i < cpColumns.size(); i++) {
				if (cpColumns.get(i).getJavaProperty() != null && !cpColumns.get(i).getJavaProperty().equals("")) {
					if (cpColumns.get(i).getReadOnly() != null && cpColumns.get(i).getReadOnly().equals("T")) {
						readOnlyColnMap.put(cpColumns.get(i).getJavaProperty(), cpColumns.get(i));
					} else {
						colnMap.put(cpColumns.get(i).getJavaProperty(), cpColumns.get(i));
					}
				}
			}
			// b.将界面字段遍历  所有的字段  有则留  添加到相应的字段
			//    拼接条件语句 update tableName set k1=v1,k2=v2 where sk1=v1
			StringBuffer keyStr = new StringBuffer("");//sql值字段+占位符
			StringBuffer keyValues = new StringBuffer("");//sql值字段值的字符串
			StringBuffer whereKey = new StringBuffer("");//条件
			StringBuffer whereKeyValues = new StringBuffer("");//条件值的字符串
			String[] tmpKV = new String[2];
			for (int i = 0; i < paramsKandV.length; i++) {
				tmpKV = paramsKandV[i].split("\\=");
				if (colnMap.containsKey(tmpKV[0])) {//可更新
					keyStr.append(tmpKV[0] + "=?,");
					keyValues.append(tmpKV[1] + "|");
				} else if (readOnlyColnMap.containsKey(tmpKV[0])) {//不可更新
					whereKey.append(" and " + tmpKV[0] + "=? ");
					whereKeyValues.append(tmpKV[1] + "|");
				}
			}
			//拼接SQL
			if (keyStr.toString().trim().equals("")) {
				returnObject.setMsg("没有修改过的字段");
				throw new RuntimeException("没有修改过的字段");
			}
			if (whereKey.toString().trim().equals("")) {
				returnObject.setMsg("更新记录的条件为空，无法更新操作！");
				throw new RuntimeException("更新记录的条件为空，无法更新操作！");
			}
			String sqlKeys = keyStr.toString().substring(0, keyStr.toString().length() - 1);
			String whereSql = whereKey.toString().substring(0, whereKey.toString().length() - 1);
			String[] valuesArr = keyValues.toString().split("\\|");
			String[] whereValue = whereKeyValues.toString().split("\\|");
			String tableName = dataStore.getUpdateTable();
			String sqlText = " update " + tableName + " set " + sqlKeys + " where 1=1 " + whereSql;
			//执行sql
			boolean flag = frameworkService.updateObject(sqlText, valuesArr, whereValue);
			if (flag) {
				returnObject.setMsg("已经成功修改！");
			} else {
				returnObject.setMsg("修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setInfo(e.getMessage());
		}
		return returnObject;
	}


	/**
	 * *
	 * 加载列表界面的权限的信息
	 *
	 * @param funcId
	 * @param colId
	 * @param dsId
	 * @param type
	 * @param flag
	 * @param request
	 * @param session
	 * @return
	 * @author feifei
	 * @date: 2015-5-13 下午02:55:27 
	 */
	@RequestMapping("/loadRightList")
	@ResponseBody
	public Map<String, List> loadRightList(String funcId, String colId, String dsId, String type, String flag, HttpServletRequest request, HttpSession session) {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.506");
		}
		Map<String, List> maps = null;
		List columnsList = new ArrayList();
		try {
			//根据dsId 加载不同页面的列集合
			String[] types = type.split(";");
			for (int i = 0; i < types.length; i++) {
				List columns = frameworkService.loadColumnsU(colId, types[i], flag, uid == null ? "" : uid.toString());
				columnsList.add(columns);
			}
			//根据当前登录人 与 模块id(funcid) 检索出 列表界面的 按钮、默认条件、所有条件、grid表格列
			maps = frameworkService.loadRightList(funcId, uid == null ? "" : uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		maps.put("list", columnsList);
		return maps;
	}
	/******** V2.0 界面Ds分离，新版本*******************************************************/
	/**
	 * 加载查询条件界面字段
	 *
	 * @param colId   即dsId
	 * @param flag
	 * @param type
	 * @param request
	 * @return
	 * @throws Exception
	 * @author Xuzq V2.0
	 * @date 2014-3-1 上午10:54:56
	 * //type : 1\2 添加，详情界面
	 * 3  	查询条件界面
	 * 4 	列表结果界面
	 */
	@RequestMapping("/loadColumnsU")
	@ResponseBody
	public List loadColumnsU(String colId, String type, String flag, HttpServletRequest request, HttpSession session) throws Exception {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.506");
		}
		List columnsList = new ArrayList();
		try {
			String[] types = type.split(";");
			for (int i = 0; i < types.length; i++) {
				List columns = frameworkService.loadColumnsU(colId, types[i], flag, uid == null ? "" : uid.toString());
				columnsList.add(columns);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columnsList;
	}

	@RequestMapping("/loadAinfoRight")
	@ResponseBody
	public Map<String, List> loadAinfoRight(String funcId, String djId, HttpServletRequest request, HttpSession session) {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.506");
		}
		Map<String, List> maps = null;
		try {
			maps = frameworkService.loadAInfoList(funcId, uid == null ? "" : uid.toString(), djId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return maps;
	}


	/**
	 * *
	 * 加载一对多弹框的所有的列和一对多包涵的信息
	 *
	 * @param mulDsId
	 * @param dsId
	 * @param coluname
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loadMulColn")
	@ResponseBody
	public QueryJson loadMulColn(String mulDsId, String dsId, String coluname, HttpServletRequest request, HttpSession session) throws Exception {
		Object uid = session.getAttribute(SessionCont.uid);
		QueryJson queryJson = new QueryJson();
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.506");
		}
		try {
			SysColumns sysColumns = frameworkService.loadSysColumns(dsId, coluname);
			//查找现有信息
			String dzTable = sysColumns.getMultiClnsTable();
			String dzShowPk = sysColumns.getMultiClnsFk();
			String showName = sysColumns.getMultiClnsDValue();
			String dzDescrib = sysColumns.getMultiClnsDescrib();
			String mulFunction = sysColumns.getMultiReturnFunc();
			String mulDsid = sysColumns.getMultiDzDsId();
			String describFlag = sysColumns.getMultiDescridFlag();
			String sameDsid = sysColumns.getMultiSameDsid();
			queryJson.setMultitable(dzTable);
			queryJson.setMultiClnsFk(dzShowPk);
			queryJson.setMultiClnsDValue(showName);
			queryJson.setMultiClnsDescrib(dzDescrib);
			queryJson.setMultiReturnFunc(mulFunction);
			queryJson.setMulDsId(mulDsid);
			queryJson.setMultiDescridFlag(describFlag);  //如果是T则返回选中的行
			queryJson.setMultiSameDsid(sameDsid);
			List<SysColumns> colu = new ArrayList<SysColumns>();
			colu = this.frameworkService.loadMulColumns(mulDsId);
			queryJson.setColumns(colu);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}


	//======================================================================================================
	//主明细加载列的方法
	//======================================================================================================

	/**
	 * 查询时调用这个方法（但是colId要传主表及明细表的colId）
	 */
	@RequestMapping("/loadQColumnsU")
	@ResponseBody
	public List loadQColumnsU(String colId, String type, String flag, HttpServletRequest request, HttpSession session) throws Exception {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.527");
		}
		List columnsList = new ArrayList();
		try {
			String[] colIds = colId.split(";");
			String[] types = type.split(";");
			for (int i = 0; i < types.length; i++) {
				List columns = frameworkService.loadColumnsU(colIds[0], types[i], flag, uid == null ? "" : uid.toString());
				columnsList.add(columns);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columnsList;
	}

	/**
	 * 添加、修改和详情的时候调用这个方法去加载列  (主明细调用)
	 *
	 * @param colId
	 * @param type
	 * @param flag
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-17 下午03:21:25
	 */
	@RequestMapping("/loadMColumnsU")
	@ResponseBody
	public List loadMColumnsU(String colId, String type, String flag, HttpServletRequest request, HttpSession session) throws Exception {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.562");
		}
		List columnsList = new ArrayList();
		try {
			String[] colIds = colId.split(";");
			String[] types = type.split(";");
			for (int i = 0; i < types.length; i++) {
				List columns = frameworkService.loadColumnsU(colIds[i], types[i], flag, uid == null ? "" : uid.toString());
				columnsList.add(columns);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columnsList;
	}

	/**
	 * 一对多（现在一对多的type为一个数字所以不能使用type循环）
	 *
	 * @param colId
	 * @param
	 * @param flag
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-4-10 上午10:10:59
	 */
	@RequestMapping("/loadOColumnsU")
	@ResponseBody
	public List loadOColumnsU(String colId, String items, String flag, HttpServletRequest request, HttpSession session) throws Exception {
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录..FrameworkController L.562");
		}
		List columnsList = new ArrayList();
		try {
			String[] colIds = colId.split(";");
			int item = Integer.parseInt(items);
			for (int i = 0; i < (item + 1); i++) {
				List columns = new ArrayList();
				if (i == 0) {
					columns = frameworkService.loadColumnsU(colIds[i], "5", flag, uid == null ? "" : uid.toString());
				} else {
					columns = frameworkService.loadColumnsU(colIds[i], "4", flag, uid == null ? "" : uid.toString());
				}
				columnsList.add(columns);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return columnsList;
	}

	/**
	 * 前台根据汉字谐音来检索数据
	 *
	 * @param dsId       去datastore中查找相应的表名
	 * @param columnName 要比对的列名
	 * @param valueStr   传入的字符串
	 * @param flag       判断是首字母查询还是其他查询  	 0：输入了商品条码，根据条码去查找商品      1：输入了商品的名称，根据商品名称去查找商品   2：输入了商品的谐音，根据商品谐音去查找商品
	 * @param qflag      判断精确查询的标志位
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-4-16 上午11:35:46
	 */
	@RequestMapping("/queryByPinYin")
	@ResponseBody
	public QueryJson queryByPinYin(DataGridReceiveParams dataGParams, String dsId, String columnName, String valueStr, String configStr, String qflag, int flag, HttpServletRequest request) throws Exception {
		QueryJson queryJson = new QueryJson();
		List list = new ArrayList();
		valueStr = valueStr.trim();
		try {
			//1.根据dsId查找 tableName
			String[] dsIds = dsId.split(";");
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			String stroeSql = dataStore.getSqlText();
			String sql = "";
			if (flag == 0 || flag == 2) {
				if ("eq".equals(qflag)) {
					sql = "select * from (" + stroeSql + ") t where t." + columnName + " = '" + valueStr + "' " + configStr;
				} else {
					sql = "select * from (" + stroeSql + ") t where t." + columnName + " like '%" + valueStr + "%' " + configStr;
				}
			} else if (flag == 1) {
				if ("eq".equals(qflag)) {
					sql = "select * from (" + stroeSql + ") t where NVL(t." + columnName + ",' ') = '" + valueStr + "'" + configStr;
				} else {
					String str = "%";
					char[] ch = valueStr.toUpperCase().toCharArray();
					for (int i = 0; i < ch.length; i++) {
						if (ch[i] == ' ') {
							str += "%";
						} else {
							str += ch[i];
						}
					}
					str += "%";
					//根据tableName，columnName，还有valueStr 拼接sql （select * from tableName t where GETCH2SPELL(t.columnName) LIKE GETCH2SPELL(valueStr)）
					sql = "select * from (" + stroeSql + ") t where GETCH2SPELL(NVL(t." + columnName + ",' ')) like GETCH2SPELL('" + str + "')" + configStr;
				}
			}
			//判断字符串valueStr 是否是字母，如果是字母还要将所有字母变换成大写  并将所有的写成 %x%x%....
			//判断是否是字符 (!Character.isLetter(字符串的每一个字母))
			//执行sql 返回list<Object>
			QueryJson tmpQJ = frameworkService.queryRowsBySqlPagination(sql.toString(), dataGParams.getPage(), dataGParams.getRows());
			System.out.print("弹窗数据：" + sql.toString());
			queryJson.setRows(tmpQJ.getRows() == null ? new ArrayList() : tmpQJ.getRows());
			queryJson.setTotal(tmpQJ.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	/**
	 * 关联查询（拉取数据）
	 *
	 * @param colName
	 * @param dsId
	 * @param relationVal
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-6-5 下午06:10:49
	 */
	@RequestMapping("/relationCol")
	@ResponseBody
	public ReturnObject relationCol(String colName, String dsId, String relationVal, HttpServletRequest request) throws Exception {
		ReturnObject returnObject = new ReturnObject();
		StringBuffer tmpBuf = new StringBuffer(" select ");
		try {
			String[] dsIds = dsId.split(";");
			List columnResult = new ArrayList(); //接收最后结果
			String[] colNames = colName.split("&");
			List<Map<String, Object>> column = this.frameworkService.onlyOneCloumn(colNames[0], dsIds[0]);//根据列名和dsId查询一个column
			if (column == null || column.isEmpty()) {
				return returnObject;
			}
			Object relationFlag = column.get(0).get("RELATION_FLAG");  //关联标志位
			Object name = column.get(0).get("NAME");  //关联标志位
			String reflag = relationFlag == null ? "" : relationFlag.toString();
			String cnameString = name.toString();
			if (!(reflag.length() == 1 && reflag.charAt(0) >= 'A' && reflag.charAt(0) <= 'Z')) {
				System.out.println("拉取信息  RELATION_FLAG 为空，请去配置！");
				return returnObject;
			}
			Object relationDsId = column.get(0).get("RELATION_DSID");
			String redsId = relationDsId == null ? "" : relationDsId.toString(); //关联表的dsId
			DataStore dataStore = this.frameworkService.getDataStoreById(redsId); //根据dsId得到dataStore
			String sql = dataStore.getSqlText();  //得到关联表的sql
			String flaglow = reflag.toLowerCase(); //将关联标志位小写
			List<Map<String, Object>> lowColumns = this.frameworkService.lowerColumns(flaglow, dsIds[0]);//根据标志位查询是这个标志位的所有的列
			Map<String, Object> tmpCln = new HashMap<String, Object>();
			Object tmpObj = null;
			Object isMulti = null;
			Object annObj = null;
			if (lowColumns != null && lowColumns.size() > 0) {
				for (int i = 0; i < lowColumns.size(); i++) {
					tmpCln = lowColumns.get(i);
					annObj = tmpCln.get("ANOTHER_NAME");
					tmpObj = tmpCln.get("NAME");
					isMulti = tmpCln.get("IS_MULTI_CLNS");
					if (isMulti != null && "T".equals(isMulti.toString())) {
						tmpBuf.append("pk_sys_ui.uf_parse_ids('" + dsIds[0] + "','" + tmpObj.toString() + "'," + annObj.toString() + ")||'-'||" + annObj.toString() + " " + tmpObj.toString() + " ");
					} else {
						tmpBuf.append(annObj + " " + tmpObj);
					}
					if (i < lowColumns.size() - 1) {
						tmpBuf.append(",");
					}
				}
				String anotherName = column.get(0).get("ANOTHER_NAME").toString();
				if (colNames.length > 1 && colNames[1] != null && colNames[1] != "") {
					anotherName = colNames[1];
				}
				tmpBuf.append(" from (" + sql + ") where  " + anotherName + " = '" + relationVal + "'");
				columnResult = this.frameworkService.execSql(tmpBuf.toString());
				returnObject.setObjList(columnResult);
			} else {
				returnObject.setObjList(new ArrayList());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;

	}

	/**
	 * 获取默认的数据
	 *
	 * @param modelReceiveObj
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-5-21 下午06:24:01
	 */
	@RequestMapping("/defaultData")
	@ResponseBody
	public List defaultData(ModelReceiveObj modelReceiveObj, HttpServletRequest request, HttpSession session) throws Exception {
		String dsid = modelReceiveObj.getDsId();
		String addQrFlag = modelReceiveObj.getAddQrFlag();
		List queryRow = frameworkService.queryDftRowByDsId(addQrFlag, dsid, session);
		return queryRow;
	}

	/**
	 * *
	 * 根据外键值找到一对多数据
	 *
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping("/getMulList")
	@ResponseBody
	public List getMulList(String dsId, String sinPkVal, String colName, String mutlId, HttpServletRequest request, HttpSession session) throws Exception {
		List list = null;
		try {
			list = frameworkService.getMultiList(dsId, sinPkVal, colName, mutlId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * *
	 * 根据外键值找到一对多数据
	 *
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping("/createNewSourceId")
	@ResponseBody
	public String createNewSourceId(String dsId, String colName, String oldSourceId, HttpServletRequest request, HttpSession session) throws Exception {
		String newSourceID = "";
		try {
			newSourceID = frameworkService.newSourceId(dsId, colName, oldSourceId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newSourceID;
	}

	/**
	 * 根据dsId得到这个ds的实体类，并且加载这个这个dsId的sys_columns
	 *
	 * @param dsId
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-22 下午02:16:01
	 */
	@RequestMapping("/dsInfoListColn")
	@ResponseBody
	public List dsInfoListColn(String dsId, HttpServletRequest request, HttpSession session) throws Exception {
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		List listAll = new ArrayList();
		List queryRow = new ArrayList();
		List colnRow = new ArrayList();
		String[] dsIds = dsId.split(";");
		DataStore dataStore = this.frameworkService.getDataStoreById(dsIds[0]);
		//权限控制
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		//拼接添加详情界面的sql
		String sql = "SELECT * FROM SYS_DATASTORE WHERE DS_ID ='" + dsIds[0] + "'";
		//权限控制结束
		if (dataStore != null) {
			queryRow = this.frameworkService.execSql(sql); //dataStore的实体
			listAll.add(queryRow);
			//根据dsId查询sys_columns（loadColumnU）
			colnRow = frameworkService.loadColumnsU(dsIds[0], "7", "", uid.toString());
			listAll.add(colnRow);
		}
		modelReturnObj.setQueryRow(queryRow);
		return listAll;
	}


	/**
	 * 返回当前系统时间
	 */
	@RequestMapping("/returnDateStr")
	@ResponseBody
	public Long returnDateStr(HttpServletRequest request) throws Exception {
		return System.currentTimeMillis() / 1000;
	}

	@RequestMapping("/queryByquanpin")
	@ResponseBody
	public QueryJson queryByquanpin(String hid, String dsId, String columnName, String valueStr, String configStr, String qflag, int flag, HttpServletRequest request) throws Exception {
		QueryJson queryJson = new QueryJson();
		List list = new ArrayList();
		try {
			String[] dsIds = dsId.split(";");
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			String stroeSql = dataStore.getSqlText();
			String sql = "";
			if (flag == 0 || flag == 2) {
				if ("eq".equals(qflag)) {
					sql = "select * from (" + stroeSql + ") t where t." + columnName + " = '" + valueStr + "' " + configStr;
				} else {
					sql = "select * from (" + stroeSql + ") t where t." + columnName + " like '%" + valueStr + "%' " + configStr;
				}
			} else if (flag == 1) {
				if ("eq".equals(qflag)) {
					sql = "select * from (" + stroeSql + ") t where NVL(t." + columnName + ",' ') = '" + valueStr + "'" + configStr;
				} else {
					String str = "%";
					char[] ch = valueStr.toUpperCase().toCharArray();
					for (int i = 0; i < ch.length; i++) {
						if (ch[i] == ' ') {
							str += "%";
						} else {
							str += ch[i];
						}
					}
					str += "%";
					sql = "select * from (" + stroeSql + ") t where GETCH2SPELL(NVL(t." + columnName + ",' ')) like GETCH2SPELL('" + str + "')" + configStr;
				}
			}
			list = this.frameworkService.execSql(sql);
			queryJson.setRows(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	@RequestMapping("/queryBydsid")
	@ResponseBody
	public QueryJson queryBydsid(String cid, String hid, String dsId, HttpServletRequest request) throws Exception {
		QueryJson queryJson = new QueryJson();
		List list = new ArrayList();
		try {
			String[] dsIds = dsId.split(";");
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			String sql = dataStore.getSqlText();
			sql = "select * from (" + sql + ") t where t.CLIENT_ID='" + cid + "' and H_ID='" + hid + "'";
			list = this.frameworkService.execSql(sql);
			queryJson.setRows(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	@RequestMapping("/dbcModifyDataPerms")
	@ResponseBody
	public String dbcModifyDataPerms(String djId, String dsId, String param, HttpSession session) {
		String isModify = "0";
		try {
			isModify = frameworkService.dbcModifyPerms(djId, dsId, session, param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isModify;
	}

	@RequestMapping("/dbcModifyColnPerms")
	@ResponseBody
	public ColnPerms dbcModifyColnPerms(String djId, String dsId, String param, HttpSession session) {
		ColnPerms colnPerms = new ColnPerms();
		try {
			colnPerms = frameworkService.dbcModifyColnPerms(djId, dsId, session, param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return colnPerms;
	}


	/**
	 * 记录操作日志
	 *
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/recordOperateLog")
	@ResponseBody
	public Boolean recordOperateLog(String dsId, String operateName, String clickEvent, HttpServletRequest request, HttpSession session) throws Exception {
		String uid = (String) session.getAttribute(SessionCont.uid);
		String operate = "insert into operateLog values('" + uid + "',sysdate,'" + dsId + "','" + operateName + "','" + clickEvent + "')";
		System.out.println("=================记录日志的语句：" + operate);
		return this.frameworkService.recordOperateLog(operate);

	}

	/**
	 * 商品动销统计
	 * lhl
	 * 需要获取时间中间隔的天数loadDataQ
	 */
	@RequestMapping("/loadDataQDate")
	@ResponseBody
	public QueryJson loadDataQDate(DataGridReceiveParams dataGParams, String dsId, String config, String originalSql, String isTotal, String qFlag, String isRep, HttpServletRequest request, HttpSession session) {
		QueryJson queryJson = new QueryJson();
		try {
			String[] dsIds = dsId.split(";");
			String date1 = "";
			String date2 = "";
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.318");
			}
			String sql = frameworkService.formatSql(dsIds[0], dataStore.getSqlText(), uid == null ? "" : uid.toString());
			if (dataStore != null) {
				StringBuffer sqlBuffer = new StringBuffer();
				StringBuffer sqlBuffer1 = new StringBuffer();
				String[] tmpValue2;
				String tmpStr = "";  //缓存语句
				String tmpStr2 = ""; //缓存语句2
				String flagA = ""; //缓存标志
				String tmpName = "";//缓存 字段
				String tmpValue = "";  //缓存值
				String editype = "";//缓存editype
				int num = 0;//存储时间间隔天数


				if (config != null && config.trim() != "") {
					String[] configS = config.split("\\|\\+");
					StringBuffer whereStr = new StringBuffer();//缓存条件语句
					for (int i = 0; i < configS.length; i++) {

						if (configS[i] != null && !"".equals(configS[i])) {
							flagA = configS[i].substring(0, 1);
							tmpStr = configS[i].substring(2, configS[i].length());

							//					*     字符串1  ：flag - ClnName - value1 -neq +
							//							eq  等于   		neq 	不等于
							//					 *      alike 以...开头  	likea　	以...结尾    inc包含
							//					 *   数值 间隔2：	 flag - date Num - value1 - value2  +
							//					 *       列表3：     flag - staId - value1;value2 +
							//					 	   时间间隔4:   flag - clnName- date1 - date2 +
							if (flagA.equals("1")) {
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")).trim();
								if ("".equals(tmpStr)) {
									continue;
								}
								//获取input框传入的参数
								String parm = tmpStr.toString().toUpperCase();
								String[] parms = parm.split(";");
								//遍历参数       对出版社简sql条件进行添加
								for (String p : parms) {
									if ("eq".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND nvl(" + tmpName + ",0) = '" + p + "' ");
											sqlBuffer1.append(" AND nvl(" + tmpName + ",0) = '" + p + "' ");
										} else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "') ");
											sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "') ");
										}
										//	sqlBuffer.append(" AND (("+tmpName+"='"+p+"') OR (upper(getch2spell(Nvl("+tmpName+",' ')))= getch2spell('"+p+"')))  ");
									} else if ("neq".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND (" + tmpName + " not in ('" + p + "'))  ");
											sqlBuffer1.append(" AND (" + tmpName + " not in ('" + p + "'))  ");
										} else {
											sqlBuffer.append(" AND  (upper(getch2spell(Nvl(" + tmpName + ",' ')))  not in getch2spell('" + p + "')) ");
											sqlBuffer1.append(" AND  (upper(getch2spell(Nvl(" + tmpName + ",' ')))  not in getch2spell('" + p + "')) ");
										}
										//sqlBuffer.append(" AND (("+tmpName+" not in ('"+p+"')) AND  upper((getch2spell(Nvl("+tmpName+",' ')))  not in getch2spell('"+p+"')))");
									} else if ("alike".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND " + tmpName + " like '" + p + "%' ");
											sqlBuffer1.append(" AND " + tmpName + " like '" + p + "%' ");
										} else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "%')  ");
											sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('" + p + "%')  ");
										}
										//	sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('"+p+"%') ");
									} else if ("likea".equals(tmpStr2)) {
										if (p.matches("^[^a-zA-Z]*$")) {
											sqlBuffer.append(" AND " + tmpName + " like '%" + p + "'");
											sqlBuffer1.append(" AND " + tmpName + " like '%" + p + "'");
										} else {
											sqlBuffer.append("  AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "')  ");
											sqlBuffer1.append("  AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "')  ");
										}
										//sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('%"+p+"') ");
									} else if ("inc".equals(tmpStr2)) {
										//判断是不是数字
										Pattern pattern = Pattern.compile("[0-9]*");
										//判断是不是负数
										Pattern pattern2 = Pattern.compile("-?[0-9]*");
										//首先判断是否包含",",如果包含，代表是并列查询
										String[] pvals = p.split(",");
										if (pvals.length > 0) {
											//((tmpName like '%1510%') or (tmpName like '%1513%'))
											StringBuffer newSql = new StringBuffer();
											for (int j = 0; j < pvals.length; j++) {
												if (j == 0) {
													if (pvals[j].matches("^[a-zA-Z]{0,}$")) {
														newSql.append(" ( upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + pvals[j] + "%') )");

													} else if (pattern.matcher(pvals[j]).matches()) {
														newSql.append(" (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													} else if (pattern2.matcher(pvals[j]).matches()) {
														newSql.append(" (" + tmpName + " = " + pvals[j] + " ) ");
													} else {
														newSql.append(" (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													}
												} else {
													if (pvals[j].matches("^[a-zA-Z]{0,}$")) {
														newSql.append(" or ( upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + pvals[j] + "%') )");
													} else {
														newSql.append(" or (" + tmpName + " like '%" + pvals[j] + "%' ) ");
													}
												}
											}
											sqlBuffer.append(" AND " + "(" + newSql + ")");
											sqlBuffer1.append(" AND " + "(" + newSql + ")");
										} else {
											//判断传入的参数不是英文
											if (p.matches("^[^a-zA-Z]*$")) {
												sqlBuffer.append(" AND " + tmpName + " like '%" + p + "%' ");
												sqlBuffer1.append(" AND " + tmpName + " like '%" + p + "%' ");
											} else {
												sqlBuffer.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "%') ");
												sqlBuffer1.append(" AND upper(getch2spell(Nvl(" + tmpName + ",' '))) like getch2spell('%" + p + "%') ");
											}
										}
									}
								}
							} else if (flagA.equals("2")) {
								//							 *    间隔2：	   flag - clnName - Num - num2  +
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								if (tmpStr.lastIndexOf("-") > tmpStr.length() + 1) {
									tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());
									sqlBuffer.append(" AND " + tmpName + " <= " + tmpStr2 + " ");
									sqlBuffer1.append(" AND " + tmpName + " <= " + tmpStr2 + " ");
								}
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-"));
								if (!"".equals(tmpStr)) {
									sqlBuffer.append(" AND " + tmpName + " >= " + tmpStr + " ");
									sqlBuffer1.append(" AND " + tmpName + " >= " + tmpStr + " ");
								}
							} else if (flagA.equals("3")) {   //3-STOCK_ID-GOM1K00000|+        3-PRINT_MAN-22378EADC22087536F54752CD5FD1CE6|+
								//							flag - staId - value1;value2 +
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());
								if ("".equals(tmpStr)) {
									continue;
								}
								tmpValue2 = tmpStr.split(";");
								tmpStr = "";
								for (int k = 0; k < tmpValue2.length; k++) {
									tmpStr += "'" + tmpValue2[k] + "'";
									if (k < tmpValue2.length - 1) {
										tmpStr += ",";
									}
								}
								sqlBuffer.append(" AND " + tmpName + " in (" + tmpStr + ")");
								sqlBuffer1.append(" AND " + tmpName + " in (" + tmpStr + ")");
							} else if (flagA.equals("4")) {
								//							时间间隔4:   flag - clnName- date1 - date2 +
								//							 input_date >  to_date('2014-5-12 00:00:00','yyyy-mm-dd hh24:mi:ss')
								//							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
								SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
								tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
								String tmpStr3 = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-"));   //第一个时间框内的值
								String tmpStr21 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //第二个时间框内的值
								date1 = tmpStr3;
								date2 = tmpStr21;
								String jqDate1 = df.format(new Date(Long.parseLong(tmpStr3)));//获取格式之后的时间
								String jqDate2 = df.format(new Date(Long.parseLong(tmpStr21)));//获取格式之后的时间
								Date d1 = df.parse(jqDate1);
								Date d2 = df.parse(jqDate2);
								long daysBetween = (d2.getTime() - d1.getTime() + 1000000)
										/ (3600 * 24 * 1000) + 1;//获取相隔天数

								num = (int) daysBetween;
								if (!"".equals(tmpStr3) && !"".equals(tmpStr21) && tmpStr3.equals(tmpStr21)) {  //两个框内都有值,，并且两个值相等
									String jqDate = df.format(new Date(Long.parseLong(tmpStr3)));
									sqlBuffer.append(" AND to_char(" + tmpName + " ,'yyyy-MM-dd')  = '" + jqDate + "'");
								} else {
									if (!"".equals(tmpStr3)) {
										sqlBuffer.append(" AND to_char(" + tmpName + ",'yyyy-MM-dd') >= '" + jqDate1 + "'");
									}
									if (!"".equals(tmpStr21)) {
										sqlBuffer.append(" AND to_char(" + tmpName + ",'yyyy-MM-dd') <= '" + jqDate2 + "'");
									}


								}
							} else if (flagA.equals("5")) {
								//5 flag - ClnName - editype - value1 -neq |+
								if ("".equals(tmpStr)) {
									continue;
								}
								String colnName = tmpStr.substring(0, tmpStr.indexOf("-"));      //列名
								String operatorFlag = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //关系运算符
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")); //dzId-value

								//

								String dzId = tmpStr.substring(0, tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());   //输入的查询条件的字符串的
								String[] valArr1 = valueStr.split(";");  //前台输入的谐音数组 NAME = CL;JK;KL;
								//								List<String> vals=new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								//								for (int j = 0; j < valArr1.length; j++) {
								//									if(valArr1[j]!=null&&valArr1[j]!=""){
								//										vals.add(valArr1[j]);
								//									}
								//								}
								String sqlForText = "select sql_text,show_pk,show_name from sys_dz_source c where c.dz_id ='" + dzId + "'";
								SysDzSource dzSource = (SysDzSource) frameworkService.sqlForList(sqlForText);
								String showName = dzSource.getShowName();
								String showPk = dzSource.getShowPk();
								String sqlText = dzSource.getSqlText();

								//								StringBuffer configSql = new StringBuffer();
								//								configSql.append(" AND ");

								String sqlConfig = " AND";
								for (int n = 0; n < valArr1.length; n++) {
									String p = valArr1[n];
									if ("eq".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' ')))= getch2spell(Nvl('" + p.trim().toUpperCase() + "',''))  ";
										} else {
											sqlConfig += " (" + showName + "='" + p + "')";
										}
									} else if ("neq".equals(operatorFlag)) {
										sqlConfig += "(" + showName + " not in ('" + p + "')) ";
									} else if ("alike".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " nvl(" + showName + ",' ') like '" + p + "%'";
										}
									} else if ("likea".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "')";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "'";
										}
									} else if ("inc".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "%'";
										}
									}
									if (n < valArr1.length - 1) {
										sqlConfig = sqlConfig + " OR";
									}
									//拼接条件
									//									configSql.append(getSql(vals,showName,sqlConfig));
								}
								//得到前台输入的条件的编码的集合
								//								String tmpSql = " select  "+showPk +" from ("+ sqlText+") A where 1=1 "+configSql;
								String tmpSql = " select  " + showPk + " from (SELECT BP.h_id, BP.h_price, nvl(PK_FX.UF_GET_RUKU(BP.H_ID), 0) AS RK_AMOUNT, nvl(PK_FX.UF_GET_CHUKU(BP.H_ID), 0) AS CK_AMOUNT, nvl(VVT.SX_AMOUNT, 0) AS SX_AMOUNT , nvl(VVT.FH_AMOUNT, 0) AS FH_AMOUNT, nvl(VVT.TH_AMOUNT, 0) AS TH_AMOUNT, nvl(VVT.GM_STOCK_AMOUNT, 0) AS GM_STOCK_AMOUNT, nvl(VVT.CP_STOCK_AMOUNT, 0) AS CP_STOCK_AMOUNT, nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0) AS KH_STOCK_AMOUNT , CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.SX_AMOUNT / " + num + "), 0) END AS RSX_AMOUNT, CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.FH_AMOUNT / " + num + "), 0) END AS RFH_AMOUNT, CASE WHEN PK_FX.UF_GET_SPDX(BP.h_id) = 0 THEN 0 ELSE NVL(round((VVT.GM_STOCK_AMOUNT + nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0)) / (PK_FX.UF_GET_SPDX(BP.h_id) / 70 * 0.5)), 0) END AS DAY_AMOUNT FROM (SELECT BP.H_ID, BP.h_price FROM BS_PRODUCT BP WHERE BP.IS_EXIST = '1' ) BP LEFT JOIN (SELECT h_id, h_price, SUM(SX_AMOUNT) AS SX_AMOUNT, SUM(FH_AMOUNT) AS FH_AMOUNT, SUM(TH_AMOUNT) AS TH_AMOUNT , SUM(GM_STOCK_AMOUNT) AS GM_STOCK_AMOUNT, SUM(CP_STOCK_AMOUNT) AS CP_STOCK_AMOUNT FROM ( SELECT * FROM (SELECT B.H_ID, B.h_price, 0 AS SX_AMOUNT, XST.FH_AMOUNT, XST.XT_AMOUNT AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, XST.input_date AS CX_DATE FROM VV_CLIENT_XSXT XST LEFT JOIN bs_product B ON B.H_ID = XST.H_ID WHERE XST.IS_STOCK = '1' AND B.IS_EXIST = '1' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM (SELECT B.H_ID, B.h_price, vv.H_AMOUNT AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, vv.import_date AS CX_DATE FROM vv_clientsales_tj vv LEFT JOIN bs_product B ON B.H_ID = vv.H_ID WHERE B.IS_EXIST = '1' AND vv.is_verify = '1' AND vv.is_destroy = '0' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM ( SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , PS.FACT_AMOUNT AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE B.IS_EXIST = '1' UNION ALL SELECT * FROM (SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, PS.FACT_AMOUNT AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE STOCK_ID = 'GOM1K00004' AND B.IS_EXIST = '1' ) ) ) TT GROUP BY h_id, h_price ) VVT ON BP.H_ID = VVT.H_ID GROUP BY BP.h_id, BP.h_price, VVT.SX_AMOUNT, VVT.FH_AMOUNT, VVT.TH_AMOUNT, VVT.GM_STOCK_AMOUNT, VVT.CP_STOCK_AMOUNT)" + sqlConfig;
								List<Map<String, String>> idList = frameworkService.execSql(tmpSql);

								StringBuffer likestr = new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append(colnName + " like '%" + idList.get(j).get(dzSource.getShowPk()) + "%'");
										if (j < (idList.size() - 1)) {
											likestr.append(" or ");
										}
									}
									sqlBuffer.append(" AND (" + likestr + ") ");
									sqlBuffer1.append(" AND (" + likestr + ") ");
								} else {
									sqlBuffer.append(" AND (0=1) ");
									sqlBuffer1.append(" AND (0=1) ");
								}
							} else if (flagA.equals("6")) {    //一对多根据ID查
								//							flag - clnName - dsid - value1;value2 +
								//根据dsid 和 name 查找对应的表  及对应的字段、
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());
								String dsid = tmpStr.substring(0, tmpStr.indexOf("-"));
								//查找出包含的所有的字段
								//只查询mul的四个字段
								//MULTI_CLNS_TABLE,MULTI_CLNS_FK,MULTI_CLNS_VALUE,MULTI_DZ_DS_ID
								SysColumns tmpOnly4P = this.frameworkService.queryColumnsMul(dsid, clnName);
								//select distinct sin_id where mul_id in (ids);
								//								sql语句 本字段   包含在这里面
								String[] idsArr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length()).split(";");
								StringBuffer tmpIds = new StringBuffer();
								//								V1.0.1
								//								for(int k = 0; k < idsArr.length; k ++){
								//									tmpIds.append("'"+idsArr[k]+"'");
								//									if (k < idsArr.length - 1) {
								//										tmpIds.append(",");
								//									}
								//								}
								//								v2.0
								for (int k = 0; k < idsArr.length; k++) {
									tmpIds.append(clnName + " LIKE '%" + idsArr[k] + "%' ");
									if (k < idsArr.length - 1) {
										tmpIds.append(" OR ");
									}
								}

								//			" AND SIN_ID IN (select distinct sin_id where mul_id in (ids))
								tmpStr = " select distinct " + tmpOnly4P.getMultiClnsFk()
										+ " from " + tmpOnly4P.getMultiClnsTable()
										+ " where " + tmpOnly4P.getMultiClnsDValue() + " in ("
										+ tmpIds + ")";
								//								sqlBuffer.append(" AND "+clnName+" in ("+tmpStr+")"); //v1.0.1
								sqlBuffer.append(" AND (" + tmpIds + ")"); //v2.0.0
								sqlBuffer1.append(" AND (" + tmpIds + ")"); //v2.0.0
							}
							//一对多的模糊查询(flag - clnName - dsid - value1;value2 -neq +)
							else if (flagA.equals("7")) {
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-")); //列名
								String operatorFlag = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //关系运算符
								tmpStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-")); //dzId-value
								String dzId = tmpStr.substring(0, tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.length());   //输入查询条件字符串
								String[] valArr1 = valueStr.split(";");  //字符串分割的谐音数组
								List<String> vals = new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								for (int j = 0; j < valArr1.length; j++) {
									if (valArr1[j] != null && valArr1[j] != "") {
										vals.add(valArr1[j]);
									}
								}
								//根据dsId，和列名查询该列一对多的的配置信息
								SysColumns mulObj = this.frameworkService.queryColumnsMul(dsId, clnName);
								SysDzSource dzSource = this.frameworkService.loadDzSource(dzId);
								if (dzSource == null) {
									throw new RuntimeException("找不到对照信息[" + mulObj.getEditypeQr() + "]用于条件查询");
								}
								String showName = dzSource.getShowName();
								String showPk = dzSource.getShowPk();
								StringBuffer sqlText = new StringBuffer(dzSource.getSqlText());

								String sqlConfig = " AND";
								for (int n = 0; n < valArr1.length; n++) {
									String p = valArr1[n];
									if ("eq".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' ')))= getch2spell(Nvl('" + p.trim().toUpperCase() + "',''))  ";
										} else {
											sqlConfig += " (" + showName + "='" + p + "')";
										}
									} else if ("neq".equals(operatorFlag)) {
										sqlConfig += "(" + showName + " not in ('" + p + "')) ";
									} else if ("alike".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " nvl(" + showName + ",' ') like '" + p + "%'";
										}
									} else if ("likea".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += "  upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "')";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "'";
										}
									} else if ("inc".equals(operatorFlag)) {
										if (p.matches("^[a-zA-Z]*$")) {
											sqlConfig += " upper(getch2spell(Nvl(" + showName + ",' '))) like getch2spell('%" + p.trim().toUpperCase() + "%') ";
										} else {
											sqlConfig += " Nvl(" + showName + ",' ') like '%" + p + "%'";
										}
									}
									if (n < valArr1.length - 1) {
										sqlConfig = sqlConfig + " OR";
									}
								}
								String tmpSql = " select  " + showPk + " from (SELECT BP.h_id, BP.h_price, nvl(PK_FX.UF_GET_RUKU(BP.H_ID), 0) AS RK_AMOUNT, nvl(PK_FX.UF_GET_CHUKU(BP.H_ID), 0) AS CK_AMOUNT, nvl(VVT.SX_AMOUNT, 0) AS SX_AMOUNT , nvl(VVT.FH_AMOUNT, 0) AS FH_AMOUNT, nvl(VVT.TH_AMOUNT, 0) AS TH_AMOUNT, nvl(VVT.GM_STOCK_AMOUNT, 0) AS GM_STOCK_AMOUNT, nvl(VVT.CP_STOCK_AMOUNT, 0) AS CP_STOCK_AMOUNT, nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0) AS KH_STOCK_AMOUNT , CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.SX_AMOUNT / " + num + "), 0) END AS RSX_AMOUNT, CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.FH_AMOUNT / " + num + "), 0) END AS RFH_AMOUNT, CASE WHEN PK_FX.UF_GET_SPDX(BP.h_id) = 0 THEN 0 ELSE NVL(round((VVT.GM_STOCK_AMOUNT + nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0)) / (PK_FX.UF_GET_SPDX(BP.h_id) / 70 * 0.5)), 0) END AS DAY_AMOUNT FROM (SELECT BP.H_ID, BP.h_price FROM BS_PRODUCT BP WHERE BP.IS_EXIST = '1' ) BP LEFT JOIN (SELECT h_id, h_price, SUM(SX_AMOUNT) AS SX_AMOUNT, SUM(FH_AMOUNT) AS FH_AMOUNT, SUM(TH_AMOUNT) AS TH_AMOUNT , SUM(GM_STOCK_AMOUNT) AS GM_STOCK_AMOUNT, SUM(CP_STOCK_AMOUNT) AS CP_STOCK_AMOUNT FROM ( SELECT * FROM (SELECT B.H_ID, B.h_price, 0 AS SX_AMOUNT, XST.FH_AMOUNT, XST.XT_AMOUNT AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, XST.input_date AS CX_DATE FROM VV_CLIENT_XSXT XST LEFT JOIN bs_product B ON B.H_ID = XST.H_ID WHERE XST.IS_STOCK = '1' AND B.IS_EXIST = '1' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM (SELECT B.H_ID, B.h_price, vv.H_AMOUNT AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, vv.import_date AS CX_DATE FROM vv_clientsales_tj vv LEFT JOIN bs_product B ON B.H_ID = vv.H_ID WHERE B.IS_EXIST = '1' AND vv.is_verify = '1' AND vv.is_destroy = '0' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM ( SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , PS.FACT_AMOUNT AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE B.IS_EXIST = '1' UNION ALL SELECT * FROM (SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, PS.FACT_AMOUNT AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE STOCK_ID = 'GOM1K00004' AND B.IS_EXIST = '1' ) ) ) TT GROUP BY h_id, h_price ) VVT ON BP.H_ID = VVT.H_ID GROUP BY BP.h_id, BP.h_price, VVT.SX_AMOUNT, VVT.FH_AMOUNT, VVT.TH_AMOUNT, VVT.GM_STOCK_AMOUNT, VVT.CP_STOCK_AMOUNT) A where 1=1 " + sqlConfig;
								//获取编码的集合
								List<Map<String, String>> idList = frameworkService.execSql(tmpSql);
								StringBuffer likestr = new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append(clnName + " like '%" + idList.get(j).get(showPk) + "%'");
										if (j < (idList.size() - 1)) {
											likestr.append(" or ");
										}
									}
									sqlBuffer.append(" AND (" + likestr + ") ");
									sqlBuffer1.append(" AND (" + likestr + ") ");
								} else {
									sqlBuffer.append(" AND (0=1) ");
									sqlBuffer1.append(" AND (0=1) ");
								}
							} else {
								throw new RuntimeException("查询条件传入有误,没有按照相关规则,请联系开发调试");
							}
						}
					}
				}
//                SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd");
//                tmpName = tmpStr.substring(0, tmpStr.indexOf("-"));
//                String tmpStr3 = tmpStr.substring(tmpStr.indexOf("-") + 1, tmpStr.lastIndexOf("-"));   //第一个时间框内的值
//                String tmpStr21 = tmpStr.substring(tmpStr.lastIndexOf("-") + 1, tmpStr.length());  //第二个时间框内的值
//                date1 = tmpStr3;
//                date2 = tmpStr21;
//                String jqDate1 = ddf.format(new Date(Long.parseLong(tmpStr3)));//获取格式之后的时间
//                String jqDate2 = ddf.format(new Date(Long.parseLong(tmpStr21)));//获取格式之后的时间
//                Date d1 = ddf.parse(jqDate1);
//                Date d2 = ddf.parse(jqDate2);
//                long daysBetween = (d2.getTime() - d1.getTime() + 1000000)/ (3600 * 24 * 1000);//获取相隔天数
				StringBuffer finalSql = new StringBuffer("select * from (SELECT BP.h_id, BP.h_price, nvl(PK_FX.UF_GET_RUKU(BP.H_ID), 0) AS RK_AMOUNT, nvl(PK_FX.UF_GET_CHUKU(BP.H_ID), 0) AS CK_AMOUNT, nvl(VVT.SX_AMOUNT, 0) AS SX_AMOUNT , nvl(VVT.FH_AMOUNT, 0) AS FH_AMOUNT, nvl(VVT.TH_AMOUNT, 0) AS TH_AMOUNT, nvl(VVT.GM_STOCK_AMOUNT, 0) AS GM_STOCK_AMOUNT, nvl(VVT.CP_STOCK_AMOUNT, 0) AS CP_STOCK_AMOUNT, nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0) AS KH_STOCK_AMOUNT , CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.SX_AMOUNT / " + num + "), 0) END AS RSX_AMOUNT, CASE WHEN " + num + " = 0 THEN 0 ELSE NVL(ROUND(VVT.FH_AMOUNT / " + num + "), 0) END AS RFH_AMOUNT, CASE WHEN PK_FX.UF_GET_SPDX(BP.h_id) = 0 THEN 0 ELSE NVL(round((VVT.GM_STOCK_AMOUNT + nvl(PK_FX.UF_GET_KHAMOUNT(BP.H_ID), 0)) / (PK_FX.UF_GET_SPDX(BP.h_id) / 70 * 0.5)), 0) END AS DAY_AMOUNT FROM (SELECT BP.H_ID, BP.h_price FROM BS_PRODUCT BP WHERE BP.IS_EXIST = '1' ) BP LEFT JOIN (SELECT h_id, h_price, SUM(SX_AMOUNT) AS SX_AMOUNT, SUM(FH_AMOUNT) AS FH_AMOUNT, SUM(TH_AMOUNT) AS TH_AMOUNT , SUM(GM_STOCK_AMOUNT) AS GM_STOCK_AMOUNT, SUM(CP_STOCK_AMOUNT) AS CP_STOCK_AMOUNT FROM ( SELECT * FROM (SELECT B.H_ID, B.h_price, 0 AS SX_AMOUNT, XST.FH_AMOUNT, XST.XT_AMOUNT AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, XST.input_date AS CX_DATE FROM VV_CLIENT_XSXT XST LEFT JOIN bs_product B ON B.H_ID = XST.H_ID WHERE XST.IS_STOCK = '1' AND B.IS_EXIST = '1' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM (SELECT B.H_ID, B.h_price, vv.H_AMOUNT AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, vv.import_date AS CX_DATE FROM vv_clientsales_tj vv LEFT JOIN bs_product B ON B.H_ID = vv.H_ID WHERE B.IS_EXIST = '1' AND vv.is_verify = '1' AND vv.is_destroy = '0' ) WHERE 'AINIT'='AINIT' UNION ALL SELECT * FROM ( SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , PS.FACT_AMOUNT AS GM_STOCK_AMOUNT, 0 AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE B.IS_EXIST = '1' UNION ALL SELECT * FROM (SELECT B.h_id, B.h_price, 0 AS SX_AMOUNT, 0 AS FH_AMOUNT, 0 AS TH_AMOUNT , 0 AS GM_STOCK_AMOUNT, PS.FACT_AMOUNT AS CP_STOCK_AMOUNT, to_char('', 'YYYY-mm-dd hh:mI:ss') AS CX_DATE FROM VV_PROD_STOCK PS LEFT JOIN bs_product B ON B.H_ID = PS.H_ID WHERE STOCK_ID = 'GOM1K00004' AND B.IS_EXIST = '1' ) ) ) TT GROUP BY h_id, h_price ) VVT ON BP.H_ID = VVT.H_ID GROUP BY BP.h_id, BP.h_price, VVT.SX_AMOUNT, VVT.FH_AMOUNT, VVT.TH_AMOUNT, VVT.GM_STOCK_AMOUNT, VVT.CP_STOCK_AMOUNT) QUERYTMP where 1 = 1  ");
				//拼接页面的查询条件sql(排除报表，所有的报表用'AINIT'='AINIT' 替换查询条件)
				if (!"true".equals(isRep)) {
					finalSql.append(sqlBuffer);
				}
				//拼接数据权限sql
				String conditionSql = frameworkService.queryConditionSql(dsId, uid.toString());


				String QcDataParam4 = "'ONEDATE'='ONEDATE'";
				if (finalSql.toString().indexOf(QcDataParam4) > 0 && !sqlBuffer.toString().trim().equals("")) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1))) {
						String jqDate = "";
						Calendar ca = Calendar.getInstance();
						ca.setTime(new Date(Long.parseLong(date1)));
						ca.set(Calendar.DAY_OF_MONTH, 1);
						ca.add(Calendar.DATE, -1);
						jqDate = (new SimpleDateFormat("yyyy-MM-dd")).format(ca.getTime());

						qcDate = " to_char(CE.DATES, 'yyyy-MM-dd') <= '" + jqDate + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam4, qcDate));
					}
				}


				String QcDataParam5 = "'TWODATE'='TWODATE'";
				if (finalSql.toString().indexOf(QcDataParam5) > 0 && !sqlBuffer.toString().trim().equals("")) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date2))) {
						String jqDate = "";
						Calendar ca = Calendar.getInstance();
						ca.setTime(new Date(Long.parseLong(date2)));
						ca.set(Calendar.DAY_OF_MONTH,
								ca.getActualMaximum(Calendar.DAY_OF_MONTH));
						jqDate = (new SimpleDateFormat("yyyy-MM-dd")).format(ca.getTime());

						qcDate = " to_char(CE.DATES, 'yyyy-MM-dd') <= '" + jqDate + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam5, qcDate));
					}
				}
				//sql中替换掉$dsid
				finalSql.toString().replace("$dsid", dsIds[0]);

				String chanParam6 = "'AINIT1'='AINIT1'";
				if (finalSql.toString().indexOf(chanParam6) > 0 && !sqlBuffer1.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer1 = new StringBuffer(sqlBuffer1.toString().replaceFirst("AND", " "));
					finalSql = new StringBuffer(finalSql.toString().replace(chanParam6, sqlBuffer1));
				}
				// 如果sql语句中包含AINIT' = 'AINIT 那么该字符串用查询条件替换掉sqlBuffer
				String chanParam = "'AINIT'='AINIT'";
				if (finalSql.toString().indexOf(chanParam) > 0 && !sqlBuffer.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer = new StringBuffer(sqlBuffer.toString().replaceFirst("AND", " "));
					finalSql = new StringBuffer(finalSql.toString().replace(chanParam, sqlBuffer));
				}

				originalSql = originalSql == null ? "" : originalSql;
				finalSql = finalSql.append(originalSql);

				System.out.println("======================#FrameworkController 750  查询生成的SQL语句" + finalSql);

				//判断是否需要分页查询
				if ("false".equals(qFlag)) {   //不需要分页
					List rows = frameworkService.execSql(finalSql.toString());
					queryJson.setRows(rows == null ? new ArrayList() : rows);
					List footRows = totalData(dsId, finalSql.toString());
					if (footRows != null && footRows.size() > 0) {
						queryJson.setFooter(footRows);
					}
					queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
				} else {
					if ("true".equals(isTotal)) {   //分页但是需要统计全部的数据
						List footRows = totalData(dsId, finalSql.toString());
						if (footRows != null && footRows.size() > 0) {
							queryJson.setFooter(footRows);
						}
					}
					QueryJson tmpQJ = frameworkService.queryRowsBySqlPagination(finalSql.toString(), dataGParams.getPage(), dataGParams.getRows());
					queryJson.setRows(tmpQJ.getRows() == null ? new ArrayList() : tmpQJ.getRows());
					queryJson.setTotal(tmpQJ.getTotal());
					queryJson.setUrl(request.getContextPath() + "/framework/loadDataQ?dsId=" + dsId + "&config=" + config);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

}
